the question is fairly simple and technical:
var it_works = false;
$.post("some_file.php", '', function(data) {
it_works = true;
});
alert(it_works); # false (yes, that 'alert' has to be here and not inside $.post itself)
What I want to achieve is:
alert(it_works); # true
Is there a way to do that? If not can $.post() return a value to be applied to it_works?
What you expect is the synchronous (blocking) type request.
Requests are asynchronous (non-blocking) by default which means that the browser won’t wait for them to be completed in order to continue its work. That’s why your alert got wrong result.
Now, with
jQuery.ajaxyou can optionally set the request to be synchronous, which means that the script will only continue to run after the request is finished.The RECOMMENDED way, however, is to refactor your code so that the data would be passed to a callback function as soon as the request is finished. This is preferred because blocking execution means blocking the UI which is unacceptable. Do it this way:
Douglas Crockford (YUI Blog)