tags:

views:

18

answers:

1

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?

+1  A: 

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 create this fiddle that demonstrates this.

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

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!

David Hoerster
That totally worked. thanks for the clarification.
Glad it worked! Yeah, they kind of hide those status values in the documentation.
David Hoerster