Catching Timeout Errors With jQuery Powered AJAX

Posted February 16, 2009 at 9:41 AM by Ben Nadel

Tags: Javascript / DHTML

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

Feb 17, 2009 at 1:55 PM // reply »
1 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.


Feb 17, 2009 at 2:33 PM // reply »
11,238 Comments

@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).


Oct 30, 2009 at 2:22 AM // reply »
1 Comments

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.


Oct 30, 2009 at 8:01 AM // reply »
11,238 Comments

@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.


Jan 3, 2010 at 8:27 PM // reply »
1 Comments

@ 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 :)


Jan 4, 2010 at 9:40 AM // reply »
11,238 Comments

@Richard,

Good point - the ajaxSetup() is definitely a good function to know about.


Jun 28, 2010 at 3:34 PM // reply »
9 Comments

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


Jun 29, 2010 at 9:43 AM // reply »
11,238 Comments

@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 :)


Sep 21, 2010 at 6:55 PM // reply »
1 Comments

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?


Sep 22, 2010 at 10:04 PM // reply »
11,238 Comments

@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.


Oct 19, 2010 at 8:20 PM // reply »
1 Comments

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


Oct 20, 2010 at 9:56 AM // reply »
11,238 Comments

@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?


Dec 28, 2010 at 3:34 PM // reply »
1 Comments

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


Oct 14, 2011 at 5:58 AM // reply »
1 Comments

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(){
}
});
}


Nov 9, 2011 at 5:00 AM // reply »
2 Comments

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


Nov 16, 2011 at 3:52 AM // reply »
1 Comments

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!


Feb 28, 2012 at 1:05 PM // reply »
1 Comments

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



Post A Comment

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.

Please review the following issues:

Author Name:


Author Email:

Author Website:

Comment:

Supported HTML tags for formatting: <strong>bold</strong>   <em>italic</em>   <code>code</code>







  • Help Wanted - Find Your Next ColdFusion Job
Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
May 17, 2013 at 7:42 PM
HashKeyCopier - An AngularJS Utility Class For Merging Cached And Live Data
Ben - thanks so much for posting these Angular articles and findings, they've been a huge help towards learning one of the more 'complex' JavaScript frameworks out there (IMO). I have been using Angu ... read »
May 16, 2013 at 5:01 PM
UPDATE: Parsing CSV Data Files In ColdFusion With csvToArray()
Your code was the closest thing I've found to obtaining some direction for converting ISO fields to values that CF can translate properly. Thank you for posting! ... read »
May 15, 2013 at 10:37 PM
Very Simple Pusher And ColdFusion Powered Chat
hi id making plz easy ... read »
May 15, 2013 at 6:07 PM
Making SOAP Web Service Requests With ColdFusion And CFHTTP
Ben, you once again saved my bacon at work. Thank you, thank you, thank you! ... read »
May 15, 2013 at 4:15 PM
What If All User Interface (UI) Data Came In Reports?
@Josh, Thanks! @Ben, I definitely recommend the David West book "Object Thinking" I've been quoting from. It goes deeply into the philosophy and history of OO programming. His breadth ... read »
May 15, 2013 at 11:36 AM
Ask Ben: Print Part Of A Web Page With jQuery
I found this helpfull when you need to keep (refresh) the original parent page after closing the iframe child print dialog (Hoping you're not using a form at this time so it won't submit again): On ... read »
May 14, 2013 at 7:13 PM
What If All User Interface (UI) Data Came In Reports?
@Jonah, If there's any books you'd recommend on the subject of domain modelling, I'd love to hear it. I just downloaded the free PDF of "Domain Driven Design Quickly". Figured I'd give it ... read »
May 14, 2013 at 6:57 PM
The UX Of Prototyping: Low-Fidelity Is The New High-Fidelity
@Phillip, I'm not sure I follow what you mean? Are you saying that you looked at the list of widgets provided by the jQuery UI and let that be your style guide? ... read »
InVision App - Prototyping Made Beautiful With Prototyping Tools