tags:

views:

23

answers:

2

I have a number of jquery asynchronous calls being called in a loop. At the end of the last call, I want the page to refresh to show the results after the call. What I have isn't working. I would appreciate some help on either why its not working or a better solution!

Thanks.

var ajaxCount = 0;

$(document).ready(function () {


    $(document).ajaxStart(function () {
        ajaxCount = 1;
    });
    $(document).ajaxStop(function () {
        ajaxCount = 0;
    });
}

function(){
    for(x loops){
        $ajax({...});
    }
    while (ajaxCount != 0) { }
    document.location = applicationRoot + 'Qc.mvc/ViewQc/' + batchId + '/1';

}
+1  A: 

.ajaxStop() fires when all concurrent ajax requests have finished, so you can just use it directly, for example:

function(){
  $(document).ajaxStop(function() {
    window.location.href = applicationRoot + 'Qc.mvc/ViewQc/' + batchId + '/1';
  });
  $ajax({...});
}

If you need the count of active AJAX requests, jQuery already maintains this, it just doesn't publicize it...it's actually what's used to determine when to fire ajaxStart and ajaxStop events. You can accedd it via $.active. In jQuery 1.5+ it's being moved to $.ajax.active.

Nick Craver
The problem is that I have other ajax calls on the page which I don't want a refresh after. Its only one particular set of ajax calls which should trigger a page refresh.
shaw2thefloor
@shaw2thefloor - That's why I'd bind *inside* the function you care about...you can bind/unbind when you want, e.g. `$(document).unbind('ajaxStop')` would stop listening for the event.
Nick Craver
Ah...I see. Thanks for that, it worked a treat.
shaw2thefloor
A: 

Why not put window.location.href = .... in the callback function of that one particular ajax call?

$(document).ajaxStart(function () {
    ajaxCount = ajaxCount + 1;
});
$(document).ajaxStop(function () {
    ajaxCount = ajaxCount - 1;
    if (ajaxCount == 0 && check if they're all fired)
            window.location.href = ...
});
zilverdistel
As I understand it, there are many calls, and he wants to redirect when they're *all* finished.
Nick Craver
I would then suggest something like this: $(document).ajaxStart(function () { ajaxCount = ajaxCount + 1; }); $(document).ajaxStop(function () { ajaxCount = ajaxCount - 1; if (ajaxCount == 0) window.location.href = ... });
zilverdistel
I tried that. I think the problem is in the while loop. It seems like it gets to the while loop and then never runs ajaxStop(); Sorry, I just changed the code above to make it more representative of what is going on.
shaw2thefloor