I am making an ajax call to the server. The code I need to run can be divided into 3 groups.
It would be ideal to run the code in group 3 after making the ajax call and before the results are back to gain the best user experience and performance.
Can this be done?
How?
ajax({ url: $(this). attr('href'), type: 'GET', async: false, cache: false, timeout: 30000, fail: function(){ return true; }, done: function(msg){ if (parseFloat(msg)){ return false; } else { return true; } } }); });
AJAX is not a programming language. AJAX just uses a combination of: A browser built-in XMLHttpRequest object (to request data from a web server) JavaScript and HTML DOM (to display or use the data)
Cut and paste whatever code you need to execute in the callback function passed to success . Some good answer is already provided.
How AJAX Calls Work. AJAX uses both a browser built-in XMLHttpRequest object to get data from the web server and JavaScript and HTML DOM to display that content to the user. Despite the name “AJAX” these calls can also transport data as plain text or JSON instead of XML.
Very simply:
function someFunction() {
//1. code that needs to run before ajax
$.ajax({...}).done(function () {
//2. code that needs to be run after the ajax call has returned
});
//3. code that needs to be run between the time the user presses
// a button and the time everything is done.
}
This works because JavaScript is synchronous in execution (unless workers are being used, but that's unrelated to this particular issue). The first bit of code will run, then the ajax call will tell the browser to start an XHR request, but someFunction
hasn't finished, so it will continue to execute synchronously.
Once someFunction
is done, the control flow will be opened up to any asynchronous events that occur, eventually leading to the done
callback.
To be fair, asynchronous event-oriented programming is not easy for most people to wrap their heads around. It's easy to lose track of what code is supposed to occur at what time.
Here's an easily executable example of how asynchronous behavior works:
(function () {
alert(1);
setTimeout(function () {
alert(2);
}, 0); //note the 0ms delay
alert(3);
}());
The order of alerts will be 1
, 3
, 2
. setTimeout
will not call its callback synchronously as it relies on waiting for the specified amount of time to elapse, so even if no time is supposed to elapse, it still has to wait for the current function to finish before it can continue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With