Ben Nadel
On User Experience (UX) Design, JavaScript, ColdFusion, Node.js, Life, and Love.
I am the chief technical officer at InVision App, Inc - a prototyping and collaboration platform for designers, built by designers. I also rock out in JavaScript and ColdFusion 24x7.
Meanwhile on Twitter
Loading latest tweet...
Ben Nadel at the New York ColdFusion User Group (May. 2008) with: Clark Valberg

Catching Timeout Errors With jQuery Powered AJAX

By Ben Nadel on

Last week, I had to create a page that would monitoring another server for up-time (during an intensive data transfer process that was crashing out the server from time to time and would need to be re-started). When coding this page, I used the jQuery AJAX Timeout setting for the first time. It was a nice little feature. I am not sure how long an AJAX request would wait before timing out if you exclude the Timeout setting; I wonder if it would ever timeout if the request simply kept hanging?

Anyway, I thought I would just throw together a quick demo so you can see part of what I was doing. First, I am going to set up a simple ColdFusion page that allows the page to be executed with an arbitrary sleep duration:

  • <!--- Param the number of milliseconds to pause. --->
  • <cfparam name="URL.timeout" type="numeric" default="1000" />
  •  
  • <!--- Pause the thread. --->
  • <cfthread
  • action="sleep"
  • duration="#URL.timeout#"
  • />
  •  
  • <!--- Return JSON success. --->
  • <cfcontent
  • type="text/plain"
  • variable="#ToBinary( ToBase64( SerializeJSON( true ) ) )#"
  • />

As you can see, this page simply sleeps the current thread and then returns a JSON response.

Now, I set up a simple page that makes an AJAX request to the above ColdFusion page making sure to get the target page to sleep longer than the AJAX timeout setting (so as to force a timeout error):

  • <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  • <html>
  • <head>
  • <title>jQuery AJAX And Timeout Demo</title>
  •  
  • <!-- Linked files. -->
  • <script type="text/javascript" src="jquery-1.3.1.pack.js"></script>
  • <script type="text/javascript">
  •  
  • $(
  • function(){
  • // Fire off AJAX request.
  • $.ajax(
  • {
  • // Define AJAX properties.
  • method: "get",
  • url: "timeout.cfm?timeout=5000",
  • dataType: "json",
  • timeout: (2 * 1000),
  •  
  •  
  • // Define the succss method.
  • success: function(){
  • $( "#response" ).text( "Success!" );
  • },
  •  
  •  
  • // Define the error method.
  • error: function( objAJAXRequest, strError ){
  • $( "#response" ).text(
  • "Error! Type: " +
  • strError
  • );
  • }
  • }
  • );
  • }
  • );
  •  
  • </script>
  • </head>
  • <body>
  •  
  • <h1>
  • jQuery AJAX And Timeout Demo
  • </h1>
  •  
  • <p>
  • Loading AJAX.....
  • </p>
  •  
  • <p id="response">
  • <!-- Reponse. -->
  • </p>
  •  
  • </body>
  • </html>

As you can see in the AJAX properties, we are getting our target page to sleep for 5,000 milliseconds but we are only allowing a 2,000 millisecond timeout for the AJAX request. When we run this page, the following content is loaded into the DOM:

Error! Type: timeout

Based on the resultant DOM content, we can see that the Timeout setting caused the AJAX request to end in error with the error handler being invoked. Just a small demo, but I think this is a setting that I want to start working into all of my jQuery AJAX applications.



Reader Comments

I think we can just provide a "Cancel" link, which the user can click and cancel the request if it's taking too long.

Reply to this Comment

@Chandra,

We can definitely take advantage of the abort() function on the XMLHttpRequest object; but, I think there its a good idea to build in a timeout as an AJAX event is supposed to be snappy and if its not, something is probably going wrong (or at least the user should be alerted in some way).

Reply to this Comment

Thanks! This helped a lot.

I think that the other helper methods like getJSON, get, post, etc. should also have provision for handling timeout and other errors. I had to replace all ajax calls to use $.ajax instead.

Reply to this Comment

@Hemanshu,

The methods like getJSON() are all wrappers to the .ajax() method. Underneath, they all use .ajax(); so, I guess the feeling is, they provide these short hands with less inputs so you don't have to provide them all. But, I agree - they probably should have error callbacks.

Reply to this Comment

@ Hemanshu

You can actually use the ajaxSetup function to give all of your queries a certain timeout value as well as other options included in the $.ajax function.

You simply use
$.ajaxSetup({ timeout: 20000
});

If you want to make it specific to each request then yes, you would have to convert all of your ajax requests to use the $.ajax function.

Hope this helps someone have a bit of time :)

Reply to this Comment

not wanting to rewrite to jQuery a complicated page already working well using Spry - Is there a Spry equivalent to
$.ajaxSetup({ timeout: 20000
});

Reply to this Comment

@Mike,

Hmm, I've never really touched Spry. I've seen it, but don't know much about the specs. Try asking Ray Camden - he's Mr. Spry :)

Reply to this Comment

I got a small problem with timeout and unreachable URLs. jQuery 1.4.2 will call the error function twice when it cannot reach the destination url.

First with status == "parsererror" and the second time with "timeout". The first results from not being able to parse the response (because there is no response).

Any ideas how to prevent that?

Reply to this Comment

@Philk,

Hmm, that's an odd one. I almost think I remember seeing this discussed somewhere. I think someone may have even said that this was the expected behavior?? But, don't quote me on that - I could be way wrong.

I don't have any good suggestions other than checking for the error type and simply exiting the method if the error is not one you want deal with.

Sorry I don't have any better advice.

Reply to this Comment

I wonder if there is a way to attach , if you will, the abort method to just one ajax function. For example , what if you have two async ajax requests? #1 keeps running, but number #2 is called, if either has error, I want to cancel and return , but it seems a bit tricky to get the function in error(ajax call #1) to return on error or cancel if the other one is still running. Did that make sense?
Thanks,
Eric Nickus
retsman

Reply to this Comment

@Eric,

I'm sorry, I'm not sure that I follow exactly what you are saying. Are both AJAX requests firing off at the same time? Or does the second one fire if the first one fails?

Reply to this Comment

Hey Ben,

I use your site pretty often so it's nice to finally put a word in ;). Maybe in jQuery 1.3.1 there was a method parameter for the $.ajax request I don't know, but in the latest 1.4.3 your method parameter is instead called type. http://api.jquery.com/jQuery.ajax/

Here's a quick sample from that page.

  • $.ajax({
  • type: "GET",
  • url: "test.js",
  • dataType: "script"
  • });

Not trying to be a nuisance, just pointing it out =).

Anyways, you're awesome man, keep it up!

-Kevin

Reply to this Comment

I am having a problem with the timeout function.

I have a setInterval wich does an ajax call. If the ajax call timesout, all other ajax requests will automatically timeout too..

Any idea how to solve this problem??

sample:

setInterval(function(){
ajaxCall();
}, 10000);

$.ajaxSetup({
timeout: 1000,
url : '/ajax/url.php',
type : 'post',
dataType: 'JSON',
cache: false
});

function ajaxCall() {
$.ajax({
success : function(r){
console.log(r);
},
error : function(){
}
});
}

Reply to this Comment

jQuery's timeout is useful specially in JSONP requests (made via the same $.ajax, but with data: 'jsonp' parameter). Thanks for this post.

Reply to this Comment

Hello, thanks a lot for this. This gave me an idea on a prototype I am working on. Also, thanks to the commentors.

$.ajaxSetup worked for me. Most of my requests are using the shorthand get, it would take much time and energy to replace 'em all.

Thanks!

Reply to this Comment

Hi Ben,

I need help with $.ajax call. currently page is taking around 45secs for URL to respond and timeout value is set as 30*1000 .
Now to avoid timeout error I increased timeout value from 30*1000 to 50*1000 , but page still timesout in 30secs.... Could you help what I am missing (using jQuery 1.4)
Thanks in advance

Reply to this Comment

Post A Comment

You — Get Out Of My Dreams, Get Into My Comments
Live in the Now
Oops!
Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.