jQuery .Ajax Error Handling Function

Posted by Ronald Eddy on Monday, April 28, 2014

jQuery Ajax Request - Background

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

//jQuery Ajax Function

$.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:

jQuery ajaxSetup Function

{% highlight javascript %}

$.ajaxSetup({ key: ‘value’ });{% endhighlight %}

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

jQuery Ajax Error Handling Function
$(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, .get, .post Example
$.ajax({
  url: "test.php"
});

or

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

or

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

Related post:

jQuery Ajax Post


comments powered by Disqus