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 handlertimeoutoption — 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.