jQuery .Ajax Error Handling Function

Categories: AJAX, jQuery

jQuery Ajax Request – Background

The jQuery library provided easy access to AJAX requests with the following functions $.get, $.post, $.ajax:

$.ajax({
  url: "test.html",
  context: document.body,
  success: function(){
    //do something on success
  }
});

The jQuery ajax error function hook is part of the callback function queues. When the callback is invoked it receives the jqXHR, a string indicating the error type, and an exception object if applicable. There are several built in error strings provided by the exception option they include “abort“, “timeout“, “No Transport“, “parser error“. We also have access to server errors that are returned. In this implementation we want to catch the following.

  1. HTTP Status Code 404 Error – ajax file not found error
  2. HTTP Status Code 500 Error – ajax internal system error
  3. AJAX JSON Parse Errors
  4. jQuery AJAX Timeout Errors
  5. jQuery AJAX Abort Errors
  6. Browser/Connectivity Errors
  7. AJAX no transport error
  8. Other Unknown Errors

jQuery .ajaxSetup() Function

It is possible to set default values for all jQuery AJAX requests using the JQuery .ajaxSetup()function. The function is used to set default key/value pairs for all future AJAX requests. Looks like this:

$.ajaxSetup({
     key: 'value'
});

jQuery Ajax Error Function

Let’s start building the function the will return the Ajax error. It will be a series of if else statements to text the chain of possible errors. We’ll test in a specific order and set an alert for each of the caught errors. We’ll also set the new function to the default error handling function with $.ajaxSetup().

Share the love!
$(function() {
	$.ajaxSetup({
		error: function(jqXHR, exception) {
			if (jqXHR.status === 0) {
				alert('Not connect.\n Verify Network.');
			} else if (jqXHR.status == 404) {
				alert('Requested page not found. [404]');
			} else if (jqXHR.status == 500) {
				alert('Internal Server Error [500].');
			} else if (exception === 'parsererror') {
				alert('Requested JSON parse failed.');
			} else if (exception === 'timeout') {
				alert('Time out error.');
			} else if (exception === 'abort') {
				alert('Ajax request aborted.');
			} else {
				alert('Uncaught Error.\n' + jqXHR.responseText);
			}
		}
	});
});

Once the default error handling action is set, you can leverage it by calling the existing jQuery ajax functions.

Ajax Error handling Examples:

// jQuery AJAX Error Handler
$.ajax({
  url: "test.php"
});

or
// jQuery AJAX Get Error Handler
$.get("test.php");

or
// jQuery AJAX post Error Handler
$.post("test.php");

10 Responses to jQuery .Ajax Error Handling Function

  1. Cordy says:

    Nice work. It’s the best answer!

  2. Joel Hernandez says:

    This code is amazing.

    I made some changes in order to “catch” mysql errors and displaying messages using jquery, depending the kind of error.

    Thanks for the effort.

  3. jigglypuff says:

    I love your blog, I have it in my rss reader and always like new things coming up from it.

  4. JJMac275 says:

    This solution outstanding! I will undoubtedly be back again!

  5. Turrell Rydman says:
    Great post – by , Oct 26, 2011

    I have been dealing with this AJAX problem for a week. This did the trick. I’ll be subscribing to your feed and I hope you write again soon.
    Cheers!

  6. Shar Koho says:

    Valuable info. Fortunate me I found your website. I bookmarked it.

  7. hokooo says:

    good solution

  8. SN says:

    Looking for the perfect solution since long time.

    Thanks for sharing.

    :)

  9. Saurhin says:

    Dear Unseen Revolution,

    need a favor, we have build an android app using SOAP AJAX calling webservices from https server, it work well on Debug mode but when exported in released ver it says

    if (jqXHR.status === 0) {
    alert(‘Unable to connect.Please verify your network connection.’);
    }

    pls help if possible

  10. admin says:

    Hi Saurhin,

    I am going to guess that you are having a cross domain scripting issue. Browsers do not allow cross-domain AJAX calls. Only cross-domain JSONP requests are allowed.

    http://api.jquery.com/jQuery.getJSON/

    http://stackoverflow.com/questions/8847893/cross-domain-issue-with-jquery

    Hope this helps!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

© 2014 - www.UnseenRevolution.com - Unseen Revolution LLC. 333 NW 4th Ave. Portland, OR 97209
5358ff0bab733
By
UnseenRevolution.com Portland, OR Category: Webinar
UnseenRevolution.com Portland, OR Category: Webinar
UnseenRevolution.com Portland, OR Category: Webinar