Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to accumulate data from various AJAX calls?

Apart from making synchronous AJAX calls if you can and think it is appropriate, what is the best way to handle something like this?

var A = getDataFromServerWithAJAXCall(whatever);
var B = getDataFromServerWithAJAXCallThatDependsOnPreviousData(A);
var C = getMoreDataFromServerWithAJAXCall(whatever2);

processAllDataAndShowResult(A,B,C);

Provided that I can pass callbacks to those functions, I know I can use closures and lambdas to get the job done like this:

var A,B,C;

getDataFromServerWithAJAXCall(whatever, function(AJAXResult) {
    A= AJAXResult;
    getDataFromServerWithAJAXCallThatDependsOnPreviousData(A, function(AJAXResult2) {
        B= AJAXResult2;
        processAllDataAndShowResult(A,B,C);
    });
});
getMoreDataFromServerWithAJAXCall(whatever2, function(AJAXResult) {
    C= AJAXResult;
    processAllDataAndShowResult(A,B,C);
});

function processAllDataAndShowResult(A,B,C) {
    if(A && B && C) {
        //Do stuff
    }
}

But it doesn't feel right or clean enough to me. So is there a better way or at least a cleaner way to do the same thing or is it just that I'm not used to javascript functional programming?

By the way, I'm using jQuery (1.4.2) if that helps.

Thank you.

like image 863
Xay Avatar asked Jun 07 '11 11:06

Xay


People also ask

Which object can be used to retrieve data in AJAX?

XMLHttpRequest (XHR) objects are used to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing. XMLHttpRequest is used heavily in AJAX programming.

Which formats are commonly used to transfer data in AJAX?

AJAX stands for Asynchronous JavaScript And XML. In a nutshell, it is the use of the XMLHttpRequest object to communicate with servers. It can send and receive information in various formats, including JSON, XML, HTML, and text files.


1 Answers

Yes, jQuery's Deferred Object is super handy.

Here's the example from the $.when() function documentation, illustrating a solution to your problem:

$.when($.ajax("/page1.php"), $.ajax("/page2.php")).done(function(a1,  a2){
    /* a1 and a2 are arguments resolved for the 
        page1 and page2 ajax requests, respectively */
   var jqXHR = a1[2]; /* arguments are [ "success", statusText, jqXHR ] */
   if ( /Whip It/.test(jqXHR.responseText) ) {
      alert("First page has 'Whip It' somewhere.");
   }
});

Cheers!

like image 70
Sébastien RoccaSerra Avatar answered Oct 12 '22 08:10

Sébastien RoccaSerra