Any way of using the data_response outside the $.post()?
This is part of the code I use:
$.post('do.php', { OP: "news_search", category: cat_id },
function(data_response){
var response = data_response; //I need to access this variable outside of $.post()
}
}, "json");
console.log(response); //response is not defined, is what I get for now
UPDATE
Is there no way of getting that response available globally?
No;
$.postexecutes asynchronously, so when you callconsole.log, the AJAX request is still running and hasn’t yet yielded a response. This is the purpose of the callback function: to provide code to be run after the request has completed. If you moveconsole.loginto the callback function, it should work:Update: If you want the response data to be globally available, you can declare the variable in the global scope like so:
Of course, the only context in which you can be sure that
responsehasactually been populated with a value is in the callback function supplied to
$.postafter the lineresponse = data_response;. If you want to use it atany other stage in the script then you’ll have to check its value first;
something like this:
Just be aware that this code won’t do anything if you put it straight after
the
$.postcall; it’ll only be useful if it’s executed after the POST request has finished, in some other asynchronous callback (perhaps a UI interaction event of some kind).