Plummer
Plummer

Reputation: 6688

jQuery .done after AJAX callback

I'm trying to run some stuff after an AJAX call is completed:

$.ajax({
    url: url,
    success: //do stuff
}).done(function (){
    $('#listings').fadeIn(800).done(function(){
        $('#loading').fadeOut(800);
    });
});

This doesn't do the last part which is $('#loading').fadeOut(800);, which should start when $('#listings').fadeIn(800) is done.

Upvotes: 3

Views: 2246

Answers (2)

Kevin B
Kevin B

Reputation: 95023

To get the promise object from an animation, use .promise.

$.ajax({
    url: url,
    success: handler
}).done(function (){
    $('#listings').fadeIn(800).promise().done(function(){
        $('#loading').fadeOut(800);
    });
});

In this particular case, it makes more sense to use a callback rather than .promise and .done on the animation. The advantage of using .promise is it results in a single callback for all selected elements rather than one callback per element. Since you're only animating one element, the callback would be the best way to do it. (adeneo's answer)

There are other advantages to using .promise, but you don't appear to need them. ($.when for example)

Upvotes: 6

adeneo
adeneo

Reputation: 318182

fadeIn() is not really the sort of function that returns a promise, but it does have a callback function you can use:

$.ajax({
    url: url,
}).done(function (){
    $('#listings').fadeIn(800, function(){
        $('#loading').fadeOut(800);
    });
});

Upvotes: 6

Related Questions