0 0 Votes

jQuery: Wait for response from POST or GET to write it to a global variable

Question by Progger99 | 18.12.2011 at 19:07

I would like to load some new data with a function in jQuery to be processed later in a different place in my global script. So far so good:

var num = 0;
 
$.get("myscript.php", {id:id}, function(response){
   num = response;
});
 
alert(num); // still 0!!!

The problem is: No matter to what I set the variable 'num' in the reload function, it is always 0 at the end! Even if I set 'num' to something different in the function by hand or if I use GET instead of POST, it is not working! Does anyone have a solution for this problem?

ReplyPositiveNegative

Stefan Trost

Show Profile | Message
2Best Answer
4 Votes

To understand this process, you have to know that the jQuery functions .post() and .get() are both running asynchronously.

This means the following: While running .post() or .get(), the script is not waiting for the answer or the result of that function. Instead, the script will immediately continue. So, before your variable can be set to another value (loading the script finally takes a little time), the variable is already outputed and therefore has still its initial value.

If you are aware of that .post() and .get() are simplifications of the function .ajax(), you can simply use the .ajax() function instead specifying, that the function should not be executed asynchronously (async:false):

var num = 0;
 
$.ajax({
   type: "GET",
   url: "myscript.php",
   async: false,
   data: {id:id},
   success: function(response) { num = response; }
});
 
alert(num);

With this, it should work. Now, the function should wait, until the value is there.
20.12.2011 at 15:16

ReplyPositive Negative
Reply

Similar Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own articles on askingbox.com. How to do.