Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global Var Javascript

I have an function in JavaScript, I try to change an global var from an function but always returns the same initial value 3:

For example: start value 3, function value 0, but always alert 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);
like image 938
blackriderws Avatar asked Feb 23 '23 04:02

blackriderws


2 Answers

The A in Ajax means asynchronous.

Your alert is being called before the request is finished, before success is called and has a chance to update the variable.

Try to move the alert into the callback function and see if that works.

like image 186
Thilo Avatar answered Feb 27 '23 09:02

Thilo


put your var test = 3; outside of the function eg:

<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>
like image 20
Book Of Zeus Avatar answered Feb 27 '23 11:02

Book Of Zeus