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?
Related Topics
Android Programming: Receive Responce from HTTP POST Request
Tutorial | 0 Comments
Android Programming: Send data via HTTP POST request
Tutorial | 0 Comments
jQuery: Read and Change Data Attribute Value
Tutorial | 0 Comments
jQuery: Send HTML5 Canvas to Server via Ajax
Tutorial | 0 Comments
JavaScript: Catch Submit of Form
Tutorial | 0 Comments
jQuery: Submit complete form and receive content with Ajax
Tutorial | 0 Comments
jQuery: CSS Stylesheet Switcher
Tutorial | 1 Comment
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.
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):
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