1

I'm trying to make some actions after an ajax call done with jquery.

I have seen that if i use a function like this:

    function DownloadData() {
        $.ajax({
            url: "/api/AlbumsRest",
            accepts: "application/json",
            cache: false,
            success: function () {
                /*binding stuff*/
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert('Error' + textStatus);
            }
        });
    }

The ajax request it's done in async mode. I don't want to change it because i don't want to freeze the page. But i would like to make some actions (animations, effects etc) after this ajax is completed.

So, my question is, how can i to know if i'm at the end of this request without using the success event

If i call DownloadData function like this:

    function DownloadNextData() {
        DownloadData();
        SlideOutAnimation();
        SlideInAnimation();
    }

I need to make slides after async request has been made.

Some idea ?

Pablo Rodríguez
  • 426
  • 1
  • 3
  • 8

3 Answers3

4

Using jQuery Deferred Objects you should return the result of $.ajax() from DownloadData

function DownloadData() {
    return $.ajax({...});
}

and then you can register a function outside of your AJAX handler that'll only get called once the AJAX call has completed:

function DownloadNextData() {
    DownloadData().done(function() {
        SlideOutAnimation();
        SlideInAnimation();
    });
}

behold - your animation processing is completely decoupled from your AJAX function :)

To simplify things, .done can also actually take a list of function references:

function DownloadNextData() {
    DownloadData().done(SlideOutAnimation, SlideInAnimation);
}

Note that in this case you can't supply your own function arguments - they'll actually get passed the contents of the AJAX data.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
2
function DownloadData() {
    return $.ajax({
        url: "/api/AlbumsRest",
        accepts: "application/json"
    });
}

function DownloadNextData() {
    SlideOutAnimation();
    SlideInAnimation();
}

DownloadData().done(DownloadNextData);
adeneo
  • 312,895
  • 29
  • 395
  • 388
  • Why did you leave `DownloadData` inside `DownloadNextData`? – Alnitak Dec 06 '12 at 18:30
  • @Alnitak - I assumed from the code in the question it just calls the ajax function once more, but I could be mistaken? Actually I think I get it now, and I'll remove it! – adeneo Dec 06 '12 at 18:32
-1

Try $.ajaxcomplete. here is the documentation for it http://api.jquery.com/ajaxComplete/

Jinal Shah
  • 325
  • 3
  • 15