Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if $.ajax error is a timeout

People also ask

Does Ajax call timeout?

Session timeout has been a very common feature in Ajax-based web applications. In responsive interface, the programmer needs to delay the ajax request to achieve some task before the response. This can be achieved by using jQuery setTimeout() function.

What is default Ajax timeout?

The default value is 0 , which means there is no timeout.

Is Ajax call blocking?

ajax has async property. If you set it to false it will block. possible duplicate of Synchronous calls with jquery -- you cannot block the runtime without blocking the browser though. And you cannot return the response from the callbacks, you have to assign it to a variable and return that one from the actual function.


If your error event handler takes the three arguments (xmlhttprequest, textstatus, and message) when a timeout happens, the status arg will be 'timeout'.

Per the jQuery documentation:

Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".

You can handle your error accordingly then.

I created this fiddle that demonstrates this.

$.ajax({
    url: "/ajax_json_echo/",
    type: "GET",
    dataType: "json",
    timeout: 1000,
    success: function(response) { alert(response); },
    error: function(xmlhttprequest, textstatus, message) {
        if(textstatus==="timeout") {
            alert("got timeout");
        } else {
            alert(textstatus);
        }
    }
});​

With jsFiddle, you can test ajax calls -- it will wait 2 seconds before responding. I put the timeout setting at 1 second, so it should error out and pass back a textstatus of 'timeout' to the error handler.

Hope this helps!