vytaux
vytaux

Reputation: 2562

Ajax request in progress jQuery

Is there a way to check if there's ajax request in progress? Something like:

if ( $.ajax.inProgress ){ do this; } else { do that; }

Upvotes: 13

Views: 27153

Answers (5)

StartCoding
StartCoding

Reputation: 393

To abort ajax request, Use

if($.active > 0){ 
ajx.abort();//where ajx is ajax variable
}

To continue running ajax request, Use

if($.active > 0){ 
return;

} 

Upvotes: 8

Gutzofter
Gutzofter

Reputation: 2023

You might like this:

$(document).ready(function() {
    var working = false;
    $("#contentLoading").ajaxSend(function(r, s) {
        $(this).show();
        $("#ready").hide();
        working = true;
    });

    $("#contentLoading").ajaxStop(function(r, s) {
        $(this).hide();
        $("#ready").show();
        working = false;
    });

    $('#form').submit(function() {
        if (working) return;
        $.post('/some/url', $(this).serialize(), function(data){
            alert(data);
        });
    });
});

Upvotes: 4

Gaurav Sharma
Gaurav Sharma

Reputation: 2848

yes there is


$.ajax({
     type: 'get',
     url: 'url',
     data: {
              email: $email.val()
     },
     dataType: 'text',
     success: function(data)
     {
        if(data == '1')
        {
            $response.attr('style', '')
                     .attr('style', "color:red;")
                     .html('Email already registered please enter a different email.');
        }
        else
        {
            $response.attr('style', '')
                     .attr('style', "color:green;")
                     .html('Available');
        }
     },
     beforeSend: function(){
                $email.addClass('show_loading_in_right')
     },
     complete: function(){
                $email.removeClass('show_loading_in_right')
     }
});


the beforeSend will do the process you need to do when the ajax request has just started and complete will be called when the ajax request is complete.
documentation

Upvotes: 13

kgiannakakis
kgiannakakis

Reputation: 104196

If you are in full control of the javascript code you could increment a variable whenever you start an ajax request and decrement it when the request completes (with success, failure or timeout). This way you always know if there is a request in progress.

Upvotes: 2

Sarfraz
Sarfraz

Reputation: 382909

You should basically set a variable on top of script set to false and on ajax initiate set it to true and in the success handler set it to false again as described here.

Upvotes: 8

Related Questions