Here is the initial code:
var res = null;
$.post('test.php', 'q=testdata', function(response) {
res = response;
});
I need to use res at some point in my code, or right after the ajax call. I tried this:
var res = null;
$.post('test.php', 'q=testdata', function(response) {
res = response;
alert('Note 1: '+res); /* Returned exactly what I wanted */
});
alert('Note 2: '+res); /* Returned null. I need to use res here. How? */
How is it possible to use res to hold the desired value after the ajax call?
Your code makes an asynchronous ajax request while the second alert executes synchronously. This means that a response may not be available when the (sequentially) second alert executes.
Try putting this behind your
$.postcall:$.ajaxSetup({async:false}).It will force the alerts to fire in the order that they appear in your code. If an async call is what you want to make, then I suggest you follow Sudhir’s advice.