SyntaxStudy
Sign Up
jQuery jQuery AJAX Error Handling
jQuery Intermediate 6 min read

jQuery AJAX Error Handling

Robust AJAX code anticipates failures — network timeouts, server errors, malformed JSON, and authentication issues. jQuery provides multiple layers of error handling from per-request callbacks to global event hooks.

Per-Request Error Handling

The .fail(callback) handler (or error option in $.ajax()) fires whenever the server returns a non-2xx status or the request times out. The callback receives the jqXHR object, a status string ('timeout', 'error', 'abort', 'parsererror'), and an exception object.

Global AJAX Events

jQuery fires document-level AJAX events that you can listen to with $(document).on('ajaxError', handler). This is ideal for showing a universal error toast or logging all failures to an analytics service without duplicating code in every request.

  • .fail() — per-request failure handler
  • timeout option — set a maximum wait time in ms
  • $(document).on('ajaxError') — global error hook
  • $(document).on('ajaxStart' / 'ajaxStop') — show/hide loading indicators

Always set a reasonable timeout value in production so stalled requests don't leave users waiting indefinitely. Combine with UI feedback — disable the trigger button and show a spinner — for a polished experience.

Example
// Per-request error handling with timeout
$.ajax({
    url    : '/api/data',
    method : 'GET',
    timeout: 5000 // 5 seconds
})
.done(function (data) {
    render(data);
})
.fail(function (xhr, status, err) {
    if (status === 'timeout') {
        alert('Request timed out. Check your connection.');
    } else {
        alert('Error ' + xhr.status + ': ' + xhr.statusText);
    }
});

// Global spinner using AJAX events
$(document)
    .on('ajaxStart', function () { $('#spinner').show(); })
    .on('ajaxStop',  function () { $('#spinner').hide(); })
    .on('ajaxError', function (e, xhr) {
        console.error('Global AJAX error:', xhr.status);
    });
Pro Tip

Always set a timeout on $.ajax() calls in production to prevent requests from hanging indefinitely.