Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parallel Ajax Calls in Javascript/jQuery

I am completely new to Javascript/jquery world and need some help. Right now, I am writing one html page where I have to make 5 different Ajax calls to get the data to plot graphs. Right now, I am calling these 5 ajax calls like this:

$(document).ready(function() {
    area0Obj = $.parseJSON($.ajax({
        url : url0,
        async : false,
        dataType : 'json'
    }).responseText);

    area1Obj = $.parseJSON($.ajax({
        url : url1,
        async : false,
        dataType : 'json'
    }).responseText);
.
.
.
    area4Obj = $.parseJSON($.ajax({
        url : url4,
        async : false,
        dataType : 'json'
    }).responseText);

    // some code for generating graphs

)} // closing the document ready function 

My problem is that in above scenario, all the ajax calls are going serially. That is, after 1 call is complete 2 starts, when 2 completes 3 starts and so on .. Each Ajax call is taking roughly around 5 - 6 sec to get the data, which makes the over all page to be loaded in around 30 sec.

I tried making the async type as true but in that case I dont get the data immediately to plot the graph which defeats my purpose.

My question is: How can I make these calls parallel, so that I start getting all this data parallely and my page could be loaded in less time?

Thanks in advance.

like image 430
Raghuveer Avatar asked Sep 14 '12 18:09

Raghuveer


2 Answers

Using jQuery.when (deferreds):

$.when( $.ajax("/req1"), $.ajax("/req2"), $.ajax("/req3") ).then(function(resp1, resp2, resp3){ 
    // plot graph using data from resp1, resp2 & resp3 
});

callback function only called when all 3 ajax calls are completed.

like image 180
gbs Avatar answered Oct 10 '22 09:10

gbs


You can't do that using async: false - the code executes synchronously, as you already know (i.e. an operation won't start until the previous one has finished).
You will want to set async: true (or just omit it - by default it's true). Then define a callback function for each AJAX call. Inside each callback, add the received data to an array. Then, check whether all the data has been loaded (arrayOfJsonObjects.length == 5). If it has, call a function to do whatever you want with the data.

like image 36
Abraham Avatar answered Oct 10 '22 08:10

Abraham