00 Votes

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

Question by Progger99 | Last update on 2021-11-02 | Created on 2011-12-18

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
2Best Answer12 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.
Last update on 2021-11-02 | Created on 2011-12-20

ReplyPositive Negative
Reply

Related 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 article on askingbox.com. That’s how it’s done.