1

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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 } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.