P.Brian.Mackey
P.Brian.Mackey

Reputation: 44295

How to signal when AJAX completes

I have two ajax $.get() requests that I need to synchronize.

Essentially

var signal1 = false;
var signal2 = false;

    $.get(url,
                {},
                function (data) { 
                    signal1 = true;//callback complete.
                },'json');

    $.get(url2,
                {},
                function (data) { 
                    signal2 = true;//callback complete.
                },'json');

    when(signal1 && signal2 == true)
       $.get(url3...

How can I, should I accomplish this type of task? (Bonus, what's the AJAX signature for failure callback?)

Upvotes: 3

Views: 838

Answers (2)

Ben Lee
Ben Lee

Reputation: 53359

You do it like this:

$.when(
    $.get(url, {}, function(data) { 
        // signal 1 complete
    }, 'json'),
    $.get(url2, {}, function(data) { 
        // signal 2 complete
    }, 'json')
).then(function() {
    // success after both methods finish
}, function() {
    // failure method
});

See jQuery.when: http://api.jquery.com/jQuery.when/

Upvotes: 3

BNL
BNL

Reputation: 7133

Look at the jquery deferred/promise methods, they are for exactly what you are trying to do.

$.when($.ajax("/page1.php"), $.ajax("/page2.php")).done(function(a1,  a2){
   // a1 and a2 are the results of your two calls.
});

http://api.jquery.com/jQuery.when/

http://api.jquery.com/deferred.promise/

Upvotes: 4

Related Questions