In short, how do I let alert(1) run first:
$.post('example.php', function() {
alert(1);
})
alert(2);
alert(3);
alert(4);
But jquery ajax call seem like run in asynchronous method. So JavaScript will run everything below first, alert(2) to alert(4), then back to the post method, alert(1).
Certainly I can just put the code in the ajax function, but this make no sense when I have dozens of functions, then I would have to add the code to all functions.
$.post('example.php', function() {
alert(1);
example();
})
function example() {
alert(2);
alert(3);
alert(4);
}
I want to get some json data from an ajax call, and use it later. So is there any smart solution?
2021-08-25
after 8 years, introduction of async / await is awesome, i don't really use jquery anymore, so i didn't test the code
await Promise.resolve($.post('example.php', function() {
alert(1);
example();
}));
alert(2);
alert(3);
alert(4);