How to execute many ajax requests and get the results in only 1 callback with jQuery $.ajax


Have you ever tried to make multiple ajax request to the server? This task becomes really chaotic if you don't know how to handle them properly (clean code, maintainability etc.). For a "beginner", the following example would do the trick:

Note: we use the cors-anywhere url before every original url to prevent CORS request errors in this example, you need to use your own URL'S:

var $requestUrlExample = "https://cors-anywhere.herokuapp.com/http://jsfiddle.net/api/user/ourcodeworld/demo/list.json";
var $requestUrlTwo = "https://cors-anywhere.herokuapp.com/http://jsfiddle.net/api/user/ourcodeworld/demo/list.json?start=1&limit=1";
var $requestUrlThree = "https://cors-anywhere.herokuapp.com/https://api.github.com/repos/sdkcarlos/artyom.js";

$.getJSON($requestUrlExample,function(resp1){
    $.getJSON($requestUrlTwo,function(resp2){
        $.getJSON($requestUrlThree,function(resp3){
            // Here all the responses will be available
            console.log(resp1);
            console.log(resp2);
            console.log(resp3);
        });
    });
});

And it works, remember "If it's stupid and it works, it ain't stupid", a simple hierarchical request example. However there's a cleaner way to achieve multiple requests and handle them with just one callback.

In this case we will use $.when function, when provides a way to execute callback functions based on zero or more objects, usually Deferred objects that represent asynchronous events .If no arguments are passed to jQuery.when(), it will return a resolved Promise. If a single Deferred is passed to jQuery.when(), its Promise object (a subset of the Deferred methods) is returned by the method.

 In the following example we will execute 3 json request to different url's with json format and we will handle all the content with just 1 callback.

var $requestUrlExample = "https://cors-anywhere.herokuapp.com/http://jsfiddle.net/api/user/ourcodeworld/demo/list.json";
var $requestUrlTwo = "https://cors-anywhere.herokuapp.com/http://jsfiddle.net/api/user/ourcodeworld/demo/list.json?start=1&limit=1";
var $requestUrlThree = "https://cors-anywhere.herokuapp.com/https://api.github.com/repos/sdkcarlos/artyom.js";

$.when($.getJSON($requestUrlExample),$.getJSON($requestUrlTwo),$.getJSON($requestUrlThree)).then(function (resp1,resp2,resp3) {
    // The request reponse will be retrieven respectively of the given order
    // Response structure : [responseContent,strinStatus("sucess" or "error"),xhrObject]
    console.log(resp1); // to retrieve the real content use resp[0]
    console.log(resp2);
    console.log(resp3);
}).fail(function (problem) {
    // handle errors (some request has failed)
    console.log(problem);
});

Obviously if 1 request fails, then you cannot retrieve the result of the other requests, but using when you'll be able to handle the error too. Play with the following fiddle which contains the previous code (navigate to Result tab):


Using the when function makes your code cleaner and compact. This feature is available since jQuery V1.5, you can read more about when function here.

Note that you can use $.ajax({url:"mypath"}) object too and not only $.get , $getJSON or $.post functions. Have fun !

Become a more social person