ajax requests hangs in chrome after connection lost

I've noticed some strange behavior in google chrome:

  • if we send post ajax request when there is no network connection, we get err_internet_disconnected exception in console (and I think, it's OK)
  • if we send long post ajax request and lose network connection during this request, google chrome doesn't abort it, there is no err_internet_disconnected exception in console and in devconsole's network tab this request is marked as pending (even after connection appear). In fact, this connection hangs and there is no opportunity to process this in js code (we expect to get ajax error, but nothing happens).

Have you any suggestions how to deal with this behavior?

EDITED: a sample of code:

$.ajax({
   url: "https://someserver.com/ws.asmx/ExecuteEx?pureJson",
   type: "POST",
   contentType: "application/json",
   data: data,
   success: function() {
      console.log("success");
   },
   error: function() {
      console.log("error");
   }
})

I tried this code in chrome dev console in this page while editing this post. Screenshot is below. The first request is my. I sent it, then unplugged network cable. The second request was failed (because of unplugged network cable). Then i plugged in network cable and the third request was successful. But the first request still has pending status (despite the loss of network connection).

devconsole's network tab

2 answers

  • answered 2017-10-11 10:17 Mohammad Trabelsi

    Try to replace the error function in $. Ajax ({ with this code and compare the results

    error: function (request, status, error) {
            console.log(request.responseText);
            console.log(request.status);
            console.log(request.error);
        }
    

    I hope that help.

  • answered 2017-10-11 10:17 Igor

    Set the timeout property. That should abort the request if connection is lost after the time out has expired.

    $.ajax({
       url: "https://someserver.com/ws.asmx/ExecuteEx?pureJson",
       type: "POST",
       contentType: "application/json",
       data: data,
       timeout: 1000, // value in milliseconds
       success: function() {
          console.log("success");
       },
       error: function() {
          console.log("error");
       }
    })
    

    See also ajax documentation

    timeout

    Set a timeout (in milliseconds) for the request. A value of 0 means there will be no timeout. This will override any global timeout set with $.ajaxSetup(). The timeout period starts at the point the $.ajax call is made; if several other requests are in progress and the browser has no connections available, it is possible for a request to time out before it can be sent.