Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery .when and multiple .load

I want to have one callback function after actions are done, I'm trying something like this:

$.when(
    $('#detail1').load('/getInfo.php'),
    $('#detail2').load('/getOther.php')
        ).then(function(a,b){
            alert("done");
        }); 

The problem is that the callback function is firing before the actions are finished.

like image 875
dimirc Avatar asked Mar 25 '12 00:03

dimirc


2 Answers

I do a similar code but for images in a more dynamic way. Hope that it help.

var deferreds = [];
// Create a deferred for all images
$('.my-img-class').each(function() {
    deferreds.push(new $.Deferred());
});
var i = 0;
// When image is loaded, resolve the next deferred
$('.my-img-class').load(function() {
    deferreds[i].resolve();
    i++;
});
// When all deferreds are done (all images loaded) do some stuff
$.when.apply(null, deferreds).done(function() { 
    // Do some stuff
});
like image 144
PierrickM Avatar answered Sep 20 '22 06:09

PierrickM


This is because jQuery.when() expects jQuery.Deferred instances while load() returns an jQuery instance (see http://api.jquery.com/jQuery.when/ and http://api.jquery.com/load/).

You can work around this issue:

// Create two Deferred instances that can be handed to $.when()
var d1 = new $.Deferred();
var d2 = new $.Deferred();

// Set up the chain of events...
$.when(d1, d2).then(function() {
    alert('done');
});

// And finally: Make the actual ajax calls:
$('#detail1').load('/getInfo.php', function() { d1.resolve(); });
$('#detail2').load('/getOther.php', function() { d2.resolve(); });
like image 25
Niko Avatar answered Sep 22 '22 06:09

Niko