blackriderws
blackriderws

Reputation: 843

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);

Upvotes: 4

Views: 179

Answers (2)

Book Of Zeus
Book Of Zeus

Reputation: 49867

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>

Upvotes: 4

Thilo
Thilo

Reputation: 262464

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.

Upvotes: 4

Related Questions