93

I'm having some problems with a jQuery control we made. Suppose you have a dropdownlist that allows you to enter the ID of the item you're looking for, and when you press ENTER or lose focus in a textbox it validates via jQuery that the ID you entered is correct, showing an alert if it doesn't.

The thing is that when an ordinary user enters an invalid value in it and loses focus by pressing the submit button, the jQuery post returns after the submit of the form has been sent.

Is there any way that I can check if there's any Async request processing by jQuery so that I do not allow the form submit?

skaffman
  • 398,947
  • 96
  • 818
  • 769
sabanito
  • 1,501
  • 1
  • 12
  • 17

5 Answers5

240

$.active returns the number of active Ajax requests.

More info here

Community
  • 1
  • 1
sivabudh
  • 31,807
  • 63
  • 162
  • 228
38

You could use ajaxStart and ajaxStop to keep track of when requests are active.

ceejayoz
  • 176,543
  • 40
  • 303
  • 368
25
 $(function () {
        function checkPendingRequest() {
            if ($.active > 0) {
                window.setTimeout(checkPendingRequest, 1000);
                //Mostrar peticiones pendientes ejemplo: $("#control").val("Peticiones pendientes" + $.active);
            }
            else {

                alert("No hay peticiones pendientes");

            }
        };

        window.setTimeout(checkPendingRequest, 1000);
 });
Aidas Bendoraitis
  • 3,965
  • 1
  • 30
  • 45
etgregor
  • 267
  • 3
  • 2
  • Seems a good solution but, Have you detected any problem with the "Maximum call stack size"? – Mikel Jul 06 '17 at 06:18
11

The $.ajax() function returns a XMLHttpRequest object. Store that in a variable that's accessible from the Submit button's "OnClick" event. When a submit click is processed check to see if the XMLHttpRequest variable is:

1) null, meaning that no request has been sent yet

2) that the readyState value is 4 (Loaded). This means that the request has been sent and returned successfully.

In either of those cases, return true and allow the submit to continue. Otherwise return false to block the submit and give the user some indication of why their submit didn't work. :)

Toji
  • 33,927
  • 22
  • 105
  • 115
  • 4
    Checking for null to determine if the request object exists is important, but if it is not null you should really check `request.readyState > 0 && request.readyState < 4` to determine a 'active' request because readyState 0 indicates that although the object has been created, a web-request has not been initiated. – Nathan Taylor Oct 08 '10 at 17:38
1

We have to utilize $.ajax.abort() method to abort request if the request is active. This promise object uses readyState property to check whether the request is active or not.

HTML

<h3>Cancel Ajax Request on Demand</h3>
<div id="test"></div>
<input type="button" id="btnCancel" value="Click to Cancel the Ajax Request" />

JS Code

//Initial Message
var ajaxRequestVariable;
$("#test").html("Please wait while request is being processed..");

//Event handler for Cancel Button
$("#btnCancel").on("click", function(){
if (ajaxRequestVariable !== undefined)

if (ajaxRequestVariable.readyState > 0 && ajaxRequestVariable.readyState < 4)
{
  ajaxRequestVariable.abort();
  $("#test").html("Ajax Request Cancelled.");
}
});

//Ajax Process Starts
ajaxRequestVariable = $.ajax({
            method: "POST",
            url: '/echo/json/',
            contentType: "application/json",
            cache: false,
            dataType: "json",
            data: {
        json: JSON.encode({
         data:
             [
                            {"prop1":"prop1Value"},
                    {"prop1":"prop2Value"}
                  ]         
        }),
        delay: 11
    },

            success: function (response) {
            $("#test").show();
            $("#test").html("Request is completed");           
            },
            error: function (error) {

            },
            complete: function () {

            }
        });
vibs2006
  • 6,028
  • 3
  • 40
  • 40