user381800
user381800

Reputation:

How to get the value of a variable from a callback of jQuery.post?

I am trying to use the return value(response) from the callback outside the jQuery.post API..how can that be done?

jQuery.post( ajaxurl, 'action', function( response ) 
{
console.log(response); // this comes back with "working"

// i tried this responseVal = response;  but didn't work            

}); 

alert(response); // this will be undefined.

So I want the alert to have access to response....Yes I know I could easily alerted it inside the callback but my application needs to access this outside.

Thanks in advance.

Upvotes: 0

Views: 131

Answers (2)

Carl
Carl

Reputation: 7554

That callback is asynchronous, so execution in your js proceeds without waiting for response to be set. In all likelihood, responseVal = response would not happen by the time the alert(responseVal) fires, so responseVal would be unset.

You can test this by initializing responseVal to some obviously "not set" value, doing the ajax call, alerting, wasting time in your script (like while(responseVal == "not set") { i++; }) and then alerting again.

I know your question says you can't make whatever use of response you need to in the success callback, but I suggest you try harder to figure out how to do so else you'll be dealing with setInterval(...) shenanigans ala @Xander's answer or setting the async=false option in jQuery.ajax(...) (along with making that request a post and setting the url, etc) and holding up execution.

Upvotes: 1

Alex
Alex

Reputation: 35409

response is out of scope when you call alert.

The following snippet executes a function that checks whether result has been set and if so clears the interval and alerts result:

var result, interval;

jQuery.post( ajaxurl, 'action', function( response ) 
{
    result = response;
}); 

interval = setInterval(function(){
    if(result !== undefined) {
        clearInterval(interval);
        alert(result); 
    }
}, 1000);

Upvotes: 1

Related Questions