Skip to content Skip to sidebar Skip to footer

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.

Solution 1:

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.

Solution 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.

Solution 3:

Let's try to do it in this way:

<scripttype="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:

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

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

publicfunctionurl2() {
    $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...

Solution 4:

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)
        });

    })

    functioncleanDataString(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 bracketsif(data !== undefined && data.toString().includes('}],success,')){ 
                temp = data.toString().split('}],success,');
                data = temp[0] + '}]';
            }
            data = JSON.parse(data);
            return data;                    // return parsed object
      }

Solution 5:

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

Post a Comment for "Parallel Ajax Calls In Javascript/jquery"