jQuery AJAX Error Handling

AJAX requests can fail for many reasons — the server might be down, the URL might be wrong, the network might be slow, or the response format might be unexpected. Proper error handling ensures your users see a clear message instead of a broken or silent page.

Common Causes of AJAX Errors

  • Wrong URL — the file or endpoint does not exist (404 error).
  • Server error — the server crashes or throws an exception (500 error).
  • Network failure — user loses internet connection.
  • Request timeout — server takes too long to respond.
  • CORS restriction — request blocked by browser's cross-origin policy.
  • Invalid JSON — server returns malformed JSON that cannot be parsed.

The error Callback in $.ajax()

$.ajax({
    url: "data.json",
    type: "GET",
    dataType: "json",
    success: function(data) {
        // handle successful response
    },
    error: function(xhr, status, error) {
        console.log("XHR Status:", xhr.status);
        console.log("Status Text:", xhr.statusText);
        console.log("Status:", status);
        console.log("Error:", error);
    }
});

The Three Error Callback Parameters

ParameterWhat It Contains
xhrThe XMLHttpRequest object with status code and response text
statusA string: "timeout", "error", "abort", "parsererror"
errorThe HTTP error description, e.g. "Not Found", "Internal Server Error"

Diagram: Error Types and Status Values

  Network disconnected  → status: "error",       xhr.status: 0
  File not found        → status: "error",       xhr.status: 404
  Server crash          → status: "error",       xhr.status: 500
  Request cancelled     → status: "abort"
  Request timed out     → status: "timeout"
  Bad JSON response     → status: "parsererror"

User-Friendly Error Messages

$.ajax({
    url: "api/products.json",
    type: "GET",
    dataType: "json",
    timeout: 5000,
    success: function(data) {
        renderProducts(data);
    },
    error: function(xhr, status) {
        var msg = "";
        if (status === "timeout") {
            msg = "Request timed out. Please check your connection.";
        } else if (xhr.status === 404) {
            msg = "Data not found. Please contact support.";
        } else if (xhr.status === 500) {
            msg = "Server error. Please try again later.";
        } else if (status === "parsererror") {
            msg = "Received invalid data from server.";
        } else {
            msg = "An unknown error occurred. Please try again.";
        }
        $("#errorBox").text(msg).show();
    }
});

Promise Style Error Handling with .fail()

$.get("products.json")
    .done(function(data) {
        console.log("Products:", data);
    })
    .fail(function(xhr, status, error) {
        $("#msg").text("Failed to load products: " + error);
    })
    .always(function() {
        $("#loader").hide();
    });

Diagram: Error Handling Flow

  $.ajax() sends request
       │
       ├─── Server responds OK (2xx) ─→ success() / .done()
       │
       ├─── Server responds error (4xx/5xx) ─→ error() / .fail()
       │
       ├─── Request times out ─→ error(xhr, "timeout") / .fail()
       │
       └─── Always runs ─→ complete() / .always()

Global AJAX Error Handler — $.ajaxSetup()

If many AJAX calls share the same error message, set a global error handler once instead of repeating it everywhere.

$(document).ready(function() {
    $.ajaxSetup({
        error: function(xhr, status, error) {
            if (xhr.status === 401) {
                window.location.href = "login.html";
            } else {
                $("#globalError").text("Something went wrong. Please try again.").show();
            }
        }
    });
});

ajaxError() — Global Event Listener

The ajaxError() method lets you attach a listener that fires whenever any AJAX request on the page fails.

$(document).ajaxError(function(event, xhr, settings, error) {
    console.log("AJAX error on:", settings.url);
    console.log("Error:", error);
    $("#globalErrorBanner").fadeIn().delay(3000).fadeOut();
});

Handling CORS Errors

CORS (Cross-Origin Resource Sharing) errors happen when your page tries to fetch data from a different domain. The browser blocks such requests unless the server explicitly allows them.

  Your page: https://mysite.com
  API call:  https://api.othersite.com/data  ← CORS error if server blocks it

  Error in console:
  "Access to XMLHttpRequest has been blocked by CORS policy"

  Solution options:
  1. Ask the API server to add: Access-Control-Allow-Origin: *
  2. Use a proxy on your own server to forward the request
  3. Use JSONP for legacy APIs that support it

Retry Logic on Failure

function fetchWithRetry(url, retries) {
    $.get(url)
        .done(function(data) {
            renderData(data);
        })
        .fail(function() {
            if (retries > 0) {
                console.log("Retrying... " + retries + " attempts left");
                setTimeout(function() {
                    fetchWithRetry(url, retries - 1);
                }, 2000);
            } else {
                $("#msg").text("Could not load data after multiple attempts.");
            }
        });
}

fetchWithRetry("api/data.json", 3);

Quick Summary

  • The error callback receives xhr, status, and error — use them for specific messages.
  • Status values: "timeout", "error", "abort", "parsererror".
  • Use xhr.status for HTTP codes: 404 (not found), 500 (server error), 0 (network failure).
  • Use $.ajaxSetup() for a site-wide default error handler.
  • Use $(document).ajaxError() to listen for all AJAX failures globally.

Leave a Comment

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