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.
That callback is asynchronous, so execution in your js proceeds without waiting for response to be set. In all likelihood,
responseVal = responsewould not happen by the time thealert(responseVal)fires, so responseVal would be unset.You can test this by initializing
responseValto some obviously “not set” value, doing the ajax call, alerting, wasting time in your script (likewhile(responseVal == "not set") { i++; }) and then alerting again.I know your question says you can’t make whatever use of
responseyou need to in the success callback, but I suggest you try harder to figure out how to do so else you’ll be dealing withsetInterval(...)shenanigans ala @Xander’s answer or setting theasync=falseoption injQuery.ajax(...)(along with making that request a post and setting the url, etc) and holding up execution.