jQuery ajax many requests with only 1 callback
Execute many request with jQuery ajax and handle all the responses with just 1 callback
HTML
<p>
The following example shows how to execute many ajax request at time and retrieve all the responses in only 1 callback.
Open the console for more information.
</p>
<input type="button" id="trigger" value="Execute 3 requests and retrieve content with only 1 callback"/><br>
<span id="loading"></span><br>
<span id="ct-resp1"></span><br>
<span id="ct-resp2"></span><br>
<span id="ct-resp3"></span><br>
JavaScript
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";
$("#trigger").click(function(){
$('#loading').text("Executing ...");
$.when($.getJSON($requestUrlExample),
$.getJSON($requestUrlTwo),
$.getJSON($requestUrlThree))
.then(function (resp1,resp2,resp3) {
$('#loading').text("Ready !");
// Handle results
// The request reponse will be retrieven respectively of the given order
console.log(resp1);$("#ct-resp1").text(JSON.stringify(resp1[0]));
console.log(resp2);$("#ct-resp1").text(JSON.stringify(resp2[0]));
console.log(resp3);$("#ct-resp1").text(JSON.stringify(resp3[0]));
}).fail(function (problem) {
// handle errors (some request has failed)
console.log(problem);
});
});