The Perfect Request

You call yourself what you want to call yourself. - Bob Dylan

Asynchronous Requests

Non-blocking Requests - allow the browser to continue working while the request is being handled.

Handling Multiple Requests

Sometimes you need to load mutiple resources into your web page, but you only want to "do something" after all of them have been handled. This implies the need of a data structure that will store all these requests for future processing.

The most simple way to do this is to use a Javascript Array:

var requests = [];  

Then we need to define the requests using $.ajax

After defining a Request, we push it into our requests Array

requests.push(cityDetails);  

If only there was a way to know when all the requests we pushed into our Array have been handled. Oh, wait!

Drumroll, please: jQuery.when

When You're Smiling

$.when(r1, r2).done(function(a, b) {
    console.log('All was handled');
});

a and b are arguments resolved for the r1 and r2 Ajax requests, respectively.

Each argument is an Array with the following structure:

[ data, statusText, jqXHR ]

So far so good, but $.when() doesn't accept an Array of Requests as an argument :(

Have no fear, .all is here!

You might want to take a look at jQuery.Deferred first, so you have an understanding of what happens next :)

The result is absolutely beautiful (http://stackoverflow.com):

$.when.all(requests).done(callback, error);

where callback is a function that gets called after all requests were handled:

var callback = function (results) {  
    /* results is an array of elements
       having the previosly described structure
       [ data, statusText, jqXHR ] */
    console.log(results);
}

and error gets called if something awful happened:

var error = function () {  
    console.log('Let's boogie!');
}

P.S. This post was inspired by The Perfect jQuery AJAX Request

Kirk out.