14

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.

Raghuveer
  • 1,413
  • 3
  • 23
  • 39

9 Answers9

28

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.

gbs
  • 3,529
  • 2
  • 20
  • 18
  • 7
    It's worth noting here that each response (resp1, resp2, resp3) will have the following structure: [ data, statusText, jqXHR ]. So you'll need to call, e.g., resp1[0] to get the actual data from the first response. – Christian Bankester Oct 24 '13 at 15:36
2

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.

Abraham
  • 20,316
  • 7
  • 33
  • 39
1

Let's try to do it in this way:

<script type="text/javascript" charset="utf-8">
    $(document).ready(function() {
        var area0Obj = {responseText:''};
        var area1Obj = {responseText:''};
        var area2Obj = {responseText:''};

        var url0 = 'http://someurl/url0/';
        var url1 = 'http://someurl/url1/';
        var url2 = 'http://someurl/url2/';

        var getData = function(someURL, place) {
            $.ajax({
                type     : 'POST',
                dataType : 'json',
                url      : someURL,
                success  : function(data) {
                    place.responseText = data;
                    console.log(place);
                }
            });
        }

        getData(url0, area0Obj);
        getData(url1, area1Obj);
        getData(url2, area2Obj);

    }); 
</script>

if server side will be smth. like this:

public function url0() {
    $answer = array(
        array('smth' => 1, 'ope' => 'one'),
        array('smth' => 8, 'ope' => 'two'),
        array('smth' => 5, 'ope' => 'three')
    );
    die(json_encode($answer));
}

public function url1() {
    $answer = array('one','two','three');
    die(json_encode($answer));
}

public function url2() {
    $answer = 'one ,two, three';
    die(json_encode($answer));
}

So there, as you can see, created one function getData() for getting data from server and than it called 3 times. Results will be received in asynchronous way so, for example, first can get answer for third call and last for first call.

Console answer will be:

[{"smth":1,"ope":"one"},{"smth":8,"ope":"two"},{"smth":5,"ope":"three"}]

["one","two","three"]

"one ,two, three"

PS. please read this: http://api.jquery.com/jQuery.ajax/ there you can clearly see info about async. There default async param value = true.

By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active...

xiaose
  • 616
  • 1
  • 7
  • 19
1

The following worked for me - I had multiple ajax calls with the need to pass a serialised object:

    var args1 = {
        "table": "users",
        "order": " ORDER BY id DESC ",
        "local_domain":""
    }
    var args2 = {
        "table": "parts",
        "order": " ORDER BY date DESC ",
        "local_domain":""
    }

    $.when(
        $.ajax({
                url: args1.local_domain + '/my/restful',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                type: "POST",
                dataType : "json",
                contentType: "application/json; charset=utf-8",
                data : JSON.stringify(args1),
                error: function(err1) {
                    alert('(Call 1)An error just happened...' + JSON.stringify(err1));
                }
            }),
        $.ajax({
            url: args2.local_domain + '/my/restful',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            type: "POST",
            dataType : "json",
            contentType: "application/json; charset=utf-8",
            data : JSON.stringify(args2),
            error: function(err2) {
                calert('(Call 2)An error just happened...' + JSON.stringify(err2));
            }
        })                     

    ).then(function( data1, data2 ) {
        data1 = cleanDataString(data1);
        data2 = cleanDataString(data2);

        data1.forEach(function(e){
            console.log("ids" + e.id)
        });
        data2.forEach(function(e){
            console.log("dates" + e.date)
        });

    })

    function cleanDataString(data){
            data = decodeURIComponent(data);
            // next if statement was only used because I got additional object on the back of my JSON object
            // parsed it out while serialised and then added back closing 2 brackets
            if(data !== undefined && data.toString().includes('}],success,')){ 
                temp = data.toString().split('}],success,');
                data = temp[0] + '}]';
            }
            data = JSON.parse(data);
            return data;                    // return parsed object
      }
Michael Nelles
  • 5,426
  • 8
  • 41
  • 57
0

In jQuery.ajax you should provide a callback method as below:

j.ajax({
        url : url0,
        async : true,
        dataType : 'json',
        success:function(data){
             console.log(data);
        }
    }

or you can directly use

jQuery.getJSON(url0, function(data){
  console.log(data);
});

reference

Anoop
  • 23,044
  • 10
  • 62
  • 76
0

You won't be able to handle it like your example. Setting to async uses another thread to make the request on and lets your application continue.

In this case you should utilize a new function that will plot an area out, then use the callback functions of the ajax request to pass the data to that function.

For example:

$(document).ready(function() {
    function plotArea(data, status, jqXHR) {
      // access the graph object and apply the data.
      var area_data = $.parseJSON(data);
    }

    $.ajax({
        url : url0,
        async : false,
        dataType : 'json',
        success: poltArea
    });

    $.ajax({
        url : url1,
        async : false,
        dataType : 'json',
        success: poltArea
    });

    $.ajax({
        url : url4,
        async : false,
        dataType : 'json',
        success: poltArea
    });

    // some code for generating graphs

}); // closing the document ready function 
dkleehammer
  • 431
  • 5
  • 17
0

It looks like you need to dispatch your request asynchronously and define a callback function to get the response.

The way you did, it'll wait until the variable is successfully assigned (meaning: the response has just arrived) until it proceeds to dispatch the next request. Just use something like this.

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: function(data) {
     area0Obj = data;
  }
});

This should do the trick.

Pedro Cordeiro
  • 2,085
  • 1
  • 20
  • 41
0

you may combine all the functionality of the different ajax functions into 1 ajax function, or from 1 ajax function, call the other functions (they would be private/controller side in this case) and then return the result. Ajax calls do stall a bit, so minimizing them is the way to go.

you can also make the ajax functions asynchronous (which then would behave like normal functions), then you can render the graph at the end, after all the functions return their data.

Teena Thomas
  • 5,139
  • 1
  • 13
  • 17
0

Here's a solution to your issue: http://jsfiddle.net/YZuD9/

lucassp
  • 4,133
  • 3
  • 27
  • 36