But for some reason, when i put variable data into naughty, it does not have content of data.
function cookie() {
var naughty = 'aaa';
$.post('/cookie', function(data) {
naughty = data;
});
alert(naughty); // sends "aaa"
}
Why?
UPDATE: thank you! now i got it, its because $.post() is async, so alert(naughty) will be executed before it will be filled with data.
Now i have sub-question: when i turn off async, will only function cookie() postpone execution or whole browser engine will freeze until AJAX is done?
UPDATE 2: Yes, @Kevin B, you are right, naughty is never filled… i did mistake in first code sample. I am lucky that all answers are valid anyway with only second code sample 🙂
As @Kevin B pointed out, async=false will be depreciated in jQuery 1.8. And it freezes browser until request is done…
sub-question #2: i have more code inside cookie(), after this AJAX request. So, can i somehow pause execution of cookie() untill AJAX is done, without freezing whole browser with async=false? Or do i have to find new way (using complete/success callback) of coding this idea?
LAST EDIT:
I realized that what i want is ASYNC:FALSE… So i simply used it. BTW. ASYNC:FALSE will NOT be removed from jQuery! Only special kind of use-case will be…
It’s a race condition. As .post() is an asynchronous function, the alert executes before naughty gets reset to data.
If you want the response to come back before continuing, you can use .ajax and set async to false.
How can I stop $.post in jQuery working asynchronously?