Determine if $.ajax error is a timeout
Asked Answered
H

1

217

I'm utilizing the magic of jQuery.ajax( settings ).

However, I'm wondering if anyone has played with the timeout setting much?

I know it's basically for dictating the local time for a request, but can it trigger anything if the timeout is reached? Or does it simply stop listening for a response?

Reading the jQuery site, I can see there are no arguments passed, so it seems like a simple setting with one capability. Which is fine.

But, I'd like to trigger an alert or some function if the timeout is reached. I can see that the error setting doesn't get triggered, in this case.

Here's my snippet:

$("form#testform").submit(function(){ 

 var allFormValues = $("form#testform").serialize(); 

   $.ajax({
    cache:false,
    timeout:8000,  // I chose 8 secs for kicks
    type:"POST",
    url:"someurl.php",
    data:allFormValues,
    error:function(){ alert("some error occurred") },
    success:function(response){ alert(response); }
   });

});

Does anyone know how to work more with timeout?

Haukom answered 22/8, 2010 at 22:17 Comment(0)
C
372

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!

Cordell answered 22/8, 2010 at 22:26 Comment(7)
Glad it worked! Yeah, they kind of hide those status values in the documentation.Cordell
They hide a lot in the documentation.Immaterial
@JochemKuijpers Fiddler will wait 2 seconds, so the timeout of 1 second is met. Read....Winnebago
@DavidHoerster your example using latest syntax since jQuery 1.8 jsfiddle.net/dcrhtL26 and see also the documentation for the .done() method for the Defered object (wrapping a promise?) api.jquery.com/deferred.doneSitsang
Can you explain what the x, t, m vars are?Chuddar
(x)mlhttprequest, (t)extstatus, and (m)essageGarret
A tip, that I learned the hard way... if async is false, the timeout is ignored! jQuery code is -> if ( s.async && s.timeout > 0 ) {Act

© 2022 - 2024 — McMap. All rights reserved.