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,246 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,246 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,246 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,246 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,246 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,246 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 24, 2013 at 11:21 AM
Strange Interaction Between DeserializeJson(), ArrayContains(), And Database Values In ColdFusion
@WebManWalking, Ha ha, let's us never speak of justifying "##" notation again :P ... read »
May 24, 2013 at 11:18 AM
Strange Interaction Between DeserializeJson(), ArrayContains(), And Database Values In ColdFusion
@Ben, Ah, so it was indeed how I vaguely remembered it to be: A direct assignment value = users.id[ i ] causes value to retain the sticky datatype of the query column. Although unnecessary in ... read »
May 24, 2013 at 9:11 AM
Preventing Links In Standalone iPhone Applications From Opening In Mobile Safari
@Brandon, Hi, No, I haven't been able to do that. I have just kept it as it is. ... read »
May 23, 2013 at 9:52 PM
Preventing Links In Standalone iPhone Applications From Opening In Mobile Safari
@Muhmmadibn Did you figure out a solution to launching PDFs? I am running into the same issues myself. There is no way to close the PDF or go back once you launch it. Thanks in advance! ... read »
May 23, 2013 at 6:06 PM
The Girl Who Broke My Heart, And Made Me A Better Person
Good day,ladies and gentle men, my name is Dr AMADI the great spell caster in Africa, i have help so many people for different kind of problems,who say there is no solution to problems on earth, that ... read »
May 23, 2013 at 4:26 PM
ColdFusion QueryAppend( qOne, qTwo )
@Heather, Glad people are still getting value out of this! ... read »
May 23, 2013 at 3:49 PM
Strange Interaction Between DeserializeJson(), ArrayContains(), And Database Values In ColdFusion
@WebManWalking, I meant the code at the bottom (not the video). I did try to experiment with an intermediary variable, like: value = users.id[ i ]; arrayContains( userIDs, value ); ... but t ... read »
May 23, 2013 at 11:06 AM
Strange Interaction Between DeserializeJson(), ArrayContains(), And Database Values In ColdFusion
@Ben, Are you talking about As Number: YES As String: YES As Java: YES? If so, that's with 3 different ways of referencing the constant 1, not users.id[1]. Query object references(*) are what seem ... read »
InVision App - Prototyping Made Beautiful With Prototyping Tools