Sequencing Ajax Requests
As the name suggests, Ajax is asynchronous, so the sequence of code might not be followed, as most of the logical activities are done when the HTTP request is completed.
How to do it ...
Let's try to understand the Ajax request with an example:
$(document).ready(function() { $.ajax({ type: "POST", url: "test.php", data:'json', data: "bar=foo", success: function(msg){ console.log('first log'); } }); console.log('second log') });
Once executed, the preceding code is seen as follows in the Firebug console:
How it works...
Although the $.ajax
function is called first, due to the asynchronous nature of the code, the second log is printed first (as this line of code follows directly after the $.ajax
function). Then, success: function
gets executed when the HTTP request is completed and, after that, first log gets printed to console.
Sequencing Ajax requests is a technique that is widely used in real-time applications. In the following...