Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check status of a jQuery ajax request

Tags:

jquery

ajax

jsonp

It seems that the success, error, and complete callbacks only fire when the ajax request is able to get some response from the server.

So if I shut down the server the following error callback is not executed and the request fails silently.

$.ajax({
  type: "GET",
  url: "http://localhost:3000/",
  dataType: "script",
  success: function() {
    alert("success");
  },
  error: function() {
    alert("error");
  }
});

What's the best way to throw an error when the server can't be reached at all.

Edit - From what I've tried and read it appears that jQuery's built in error handling doesn't work with JSONP, or dataType: "script". So I'm going to try setting a manual timeout.

Edit - Did a little more research and it looks like not only does the ajax error callback not work, but you can't abort an ajax request with dataType script or jsonp, and those requests ignore the timeout setting.

There is an alternative - the jquery-jsonp plugin, but it uses hidden iframes which I'd rather avoid. So I've settled on creating a manual timeout as suggested below. You can't abort the request if it times out, which means the script may still load even after the timeout, but at least something will fire if the server is unavailable.

like image 340
Seth Archer Brown Avatar asked Jul 02 '10 04:07

Seth Archer Brown


People also ask

How do I know if AJAX request is running jQuery?

jQuery ajaxStop() Method The ajaxStop() method specifies a function to run when ALL AJAX requests have completed. When an AJAX request completes, jQuery checks if there are any more AJAX requests. The function specified with the ajaxStop() method will run if no other requests are pending.

How do I know if AJAX request is successful?

You can check when exactly it returns "success" : // If successful, handle type chaining if ( status >= 200 && status < 300 || status === 304 ) { ... // If not modified if ( status === 304 ) { statusText = "notmodified"; ... // If we have data } else { try { ...

Does AJAX wait for response?

Ajax requests do just that. With this, all codes following this one will execute immediately; you will not have to wait until the function returns. This way, your user would not have to wait for findItem() to return a result. Of course, because you still need an answer, you would have to include a callback.


1 Answers

You can use a setTimeout, and clear it with clearTimeout in the complete handler.

var reqTimeout = setTimeout(function()
{
  alert("Request timed out.");
}, 5000);
var xhr = $.ajax({
  type: "GET",
  url: "http://localhost:3000/",
  dataType: "script",
  success: function() {
    alert("success");
  },
  error: function() {
    alert("error");        
  },
  complete: function() {
    clearTimeout(reqTimeout);
  }
});
like image 115
Matthew Flaschen Avatar answered Oct 19 '22 06:10

Matthew Flaschen