1

I have a simple page, with binding ajaxSend event. When it fires a new class "ajax-loading" appends to a specific element. And second bind is for ajaxComplete, when it fires, a class "ajax-loading" removes from element. And the problem is, when i have two asynchronous ajax requests.

They starts fast and seems like immediately, but when first ajaxComplete fired, a class "ajax-loading" is removed. although second ajax is not yet completed.

How can i keep "ajax-loading" until second ajaxComplete fired ? The code is simple:

    $('h1').bind('ajaxSend', function() {
        $(this).addClass('ajax-loading');
    }).bind('ajaxComplete', function() {
        $(this).removeClass('ajax-loading');
    });
    $('h1').click(function() {
        $.get('');
        $.get('');
    });

2 Answers 2

2

You could implement a counter. Instead of using a JavaScript variable, you can also attach it to the element, using .data().

var ajaxRequests = 0;
$('h1').bind('ajaxSend', function() {
    ajaxRequests++; //Increase counter
    $(this).addClass('ajax-loading');
}).bind('ajaxComplete', function() {
    if (--ajaxRequests == 0) { // Decrease counter by one, and check for zero
        $(this).removeClass('ajax-loading');
    }
});
$('h1').click(function() {
    $.get('');
    $.get('');
});
3
  • 1
    @RusAlex If the requests don't have to be fired simultaneously, it's the best solution. If the requests are always fired with each other, pimvdb's solution is also a decent choice.
    – Rob W
    Oct 30, 2011 at 9:46
  • 1
    I think you should check for 2 instead.
    – pimvdb
    Oct 30, 2011 at 9:46
  • 2
    @pimvdb No, that would break the code for the next time. I have just ninja-edited my answer, and added -- (--ajaxRequests) to get it work all the time. Note that it doesn't matter how many AJAX requests are fired, as long as they're completed, the loader is removed.
    – Rob W
    Oct 30, 2011 at 9:49
1

I suggest using Deferred:

$('h1').addClass('ajax-loading');

$.when($.get(''), $.get(''))
 .then(function() {
     $('h1').removeClass('ajax-loading');
 });

It will only remove it when both are completed.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.