Global Var Javascript

I have a function in JavaScript, I'm trying to change the global var from a function, but it always returns the same initial value of 3:

For example: initial value 3, function value 0, but always warning 3.

var test = 3; jQuery.ajax({ type: "POST", url: "ajax_js.php", data: String, success: function(result){ test = result; if(result == 0){ $('input[name=user_name]').val(''); } } }); alert( test); 
+4
source share
2 answers

A in Ajax means asynchronous.

Your alert is called before the request is completed, before success is called and has the ability to update the variable.

Try translating the warning into a callback function and see if this works.

+4
source

put your var test = 3; out of function, for example:

 <script type="text/javascript"> var test = 3; $('#button').click(function() { jQuery.ajax({ type: "POST", url: "ajax_js.php", data: String, success: function(result){ test = result; alert( test); if(result == 0){ $('input[name=user_name]').val(''); } } }); }); </script> 
+4
source

Source: https://habr.com/ru/post/1369092/


All Articles