Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firing callback after multiple ajax requests are complete

loadInfo: function(){
    var jsonCounter = 0,
    room = ['room1','room2','room3'],
    dates = [],
    prices = []

    $.each(booking.rooms, function(key, room_name) {
        $.getJSON('/get_info.php?room='+room_name, function(data) {
            dates[room_name] = data
            jsonCounter++
        })
        $.getJSON('/get_info.php?room='+room_name+'&prices', function(data) {
            prices[room_name] = data
            jsonCounter++
        })

    })

    function checkIfReady() {
        if (jsonCounter === rooms.length * 2) {
            clearInterval(timer)
            run_the_rest_of_the_app()
        }
    }

    var timer = setInterval(checkIfReady, 100)

}

(Modified a lot, as it's part of a class etc etc.)

At the moment this feels a bit hackish, as the timer usage seems rubbish. I would use $.when and $.done, but I don't know how many rooms there might be, so I don't know what to put into when.

How do I ensure that run_the_rest_of_the_app() only gets called once all of the AJAX requests come back?

like image 521
Rich Bradshaw Avatar asked Apr 09 '12 15:04

Rich Bradshaw


2 Answers

  • var activeAJAX = 0;

  • Before making an AJAX call, activeAJAX++;

  • After completing an AJAX call (in the callback): if (--activeAJAX == 0) { allDone(); }

like image 154
Amadan Avatar answered Oct 20 '22 11:10

Amadan


Here is how to use when/done

loadInfo: function(){
    var room = ['room1','room2','room3'],
    dates = [],
    prices = [],
    requests = [];

    $.each(booking.rooms, function(key, room_name) {
        var aRequest;

        aRequest = $.getJSON('/get_info.php?room='+room_name, function(data) {
            dates[room_name] = data;
        });
        requests.push(aRequest);

        aRequest = $.getJSON('/get_info.php?room='+room_name+'&prices', function(data) {
            prices[room_name] = data;
        });
        requests.push(aRequest);

    })

    $.when.apply($, requests).done(run_the_rest_of_the_app);
}
like image 29
Gabriele Petrioli Avatar answered Oct 20 '22 09:10

Gabriele Petrioli