Neigyl R. Noval
Neigyl R. Noval

Reputation: 6038

jquery ajax get result

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?

Upvotes: 1

Views: 483

Answers (2)

Abbas
Abbas

Reputation: 6886

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 $.post call: $.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.

Upvotes: 2

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100205

Will something of this kind help you:

var res = null;
$.post('test.php', 'q=testdata', function(response) {
   res = response;
   doSomething(res);
});

function doSomething(respo) {
  //do someting with response
}

Upvotes: 1

Related Questions