Call ajax in parallel instead of in a chain

We know ajax is an asynchronous call and doesn’t halts other ajax calls if calls are made same time.

Suppose I have a button and clicking on that button fires two ajax calls.

So when i click the button then both ajax get called same time and these calls don’t have any dependency to each other.

But there are situation where we need to do something else when both ajax call get completed like refreshing a section or showing success message.
For doing this we need know on which state all my ajax are completed. And its not necessary that ajax will be get completed in the same sequence I called.

$.post('page1.php',function(data1){});
$.post('page2.php',function(data2){});
$.post('page3.php',function(data3){});

Suppose i have these 3 ajax calls. Now i need to show an success message to user when all these are completed.
There are no way to do it if we make ajax calls in parallel.

So to make it simplified we made ajax call in chain means we call an ajax first and when that ajax completes then we call the 2nd ajax and so on.
When my last ajax call gets completed then we show the required message to the user because we are very sure that my ajax call gets fired because only when all my previous ajax are completed successfully.

Like

$.post('page1.php',function(data1){
    $.post('page2.php',function(data2){
        $.post('page3.php',function(data3){
            //Here we make sure all ajax call completed
        });
    });
});

Above code doesn’t has any problem at all, that code structure is very well trusted and never fails.

But don’t you think you are just wasting time because ajax will be call one by one and next subsequent call will fired only when previous one completed successfully.
Also ajax are ment to call asynchronously so you will able to call all 3 ajax parallel.

Now if you are able to detect the complete point of all 3 ajax calls then it will be big performace boosting.

We can do this by using jQuery deferred object.

We will use $.when() function, inside this function we will pass all ajax call and we will catch all ajax state using $.done() or $.then().

$.when(
    $.post('page1.php'),
    $.post('page2.php'),
    $.post('page3.php')
).done(function(data1, data2, data3){
    //here you will all 3 ajax calls response available when all
ajax call get completed.
});
$.when(   
    $.post('page1.php'),
    $.post('page2.php'),
    $.post('page3.php')
).then(function(data1, data2, data3){
    //here you will all 3 ajax calls response available when all
ajax call get completed.
});

If you want to call a specific success function if all gets completed successfully or call a failure function if one of the call failed then do it like.

$.when(
    $.post('page1.php'),
    $.post('page2.php'),
    $.post('page3.php')
).then(successCallBack, failureCallBack);