4

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

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Youre Right, But do you know how i can make for call first the success function before alert? :)
If you need something to happen after success, you need to move that code into the function success.
4

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.