Jim
Jim

Reputation: 521

Elegant javascript - making function fire when 3 different AJAX requests have happened

I have three different AJAX queries that I want to hit various services. When they've all come back (or timed out) I'd like them to call a function.

I can imagine lots of ways of doing this, like having an intermediate function count when all the requests have come in, but is there a beautiful solution?

Upvotes: 1

Views: 91

Answers (4)

hunter
hunter

Reputation: 63542

You can accomplish this easily with jQuery using the complete callback

var checked = 0;

$(function() {
    $.ajax({ url: "1st ajax", complete: function(){ checked++; Check(); }});
    $.ajax({ url: "2nd ajax", complete: function(){ checked++; Check(); }});
    $.ajax({ url: "3rd ajax", complete: function(){ checked++; Check(); }});
}

function Check() {
    if (checked >= 3) {
        // all 3 have been successfully completed or timedout
    }
}

or using then() deferred object to call the sequentially:

$.get("1st ajax").then(function(){ 
    $.get("2nd ajax").then(function(){ 
        $.get("3rd ajax").then(function(){ 
            // call something
        });
    });
});

or using then() deferred object to call them without waiting with Check() method:

$.get("1st ajax").then(function(){ checked++; Check(); });
$.get("2nd ajax").then(function(){ checked++; Check(); });
$.get("3rd ajax").then(function(){ checked++; Check(); });

Upvotes: 0

dgvid
dgvid

Reputation: 26633

If you are using jQuery 1.5 or later, you can use the jQuery.when method. For example:

$.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.");
           }
});

Otherwise, see the Promises/A design pattern.

Upvotes: 0

hvgotcodes
hvgotcodes

Reputation: 120268

jQuery allows you to do what you want. See

http://www.erichynds.com/jquery/using-deferreds-in-jquery/

Naturally this only works if you are using jQuery, or can use jQuery.

Upvotes: 3

Frank Allenby
Frank Allenby

Reputation: 4392

Hmm, maybe you could have a boolean value set to true once the last function called is executed fully? I suppose that this would pose a problem if the functions are being executed asynchronously, though.

Upvotes: -1

Related Questions