How to display error messages and details of error occurred during jQuery AJAX Call

Dani AI

Generated

Good start by — the global handler, the error callback in $.ajax, and attaching .fail to the returned jqXHR are the right building blocks. To make error reporting useful to users and actionable for debugging, normalize the inputs you get from jQuery (the jqXHR, textStatus, and errorThrown) into a single message payload and then map that payload to either inline form errors, a toast, or a generic alert.

Here is a compact pattern that extracts HTTP status, handles timeouts/network problems, prefers responseJSON when available, and falls back to parsing responseText. It also assembles field-level validation messages when the server returns them:

var req = $.ajax({
  url: '/api/your-endpoint',
  method: 'POST',
  data: formData,
  dataType: 'json',
  timeout: 15000
});

req.done(function(data){
  // success
});

req.fail(function(jqXHR, textStatus, errorThrown){
  console.error('AJAX failed:', textStatus, errorThrown, jqXHR);
  var userMsg = 'An unexpected error occurred.';

  if (textStatus === 'timeout') {
    userMsg = 'Request timed out. Please try again.';
  } else if (jqXHR.status === 0) {
    userMsg = 'Network error. Check your connection.';
  } else if (jqXHR.status >= 500) {
    userMsg = 'Server error. Try again later.';
  } else {
    var body = jqXHR.responseJSON;
    if (!body && jqXHR.responseText) {
      try { body = JSON.parse(jqXHR.responseText); } catch(e){}
    }
    if (body && body.message) userMsg = body.message;
    else if (body && body.errors) {
      userMsg = Object.keys(body.errors).map(function(k){
        return k + ': ' + body.errors[k].join(', ');
      }).join('\n');
    } else if (errorThrown) userMsg = errorThrown;
  }

  // show userMsg in the UI (inline, toast, etc.)
});

Troubleshooting notes and best practices: use the browser Network tab to inspect request/response, ensure the server returns proper HTTP status codes (400/422 for validation, 401 for auth, 500 for server errors) and a consistent JSON error schema so responseJSON works reliably. Be careful with dataType: 'json' — it helps populate responseJSON but will produce a parsererror if the server returns non-JSON. For cross-origin calls verify CORS headers. Never display raw stack traces to users; log full details to server logs or an error tracker and present a short, localizable message in the UI. For consistent UX, centralize error handling (a wrapper or a $(document).ajaxError hook) so all AJAX calls behave the same.

There are multiple ways:

  1. Global ajax error events in jQuery: https://api.jquery.com/ajaxError/
  2. Attach .fail to jqXHR object; example here; https://api.jquery.com/jQuery.get/
  3. You can pass the error key and handler function in the $.ajax function
$.ajax({
  ...
  error: function() {
    // handle error here
  },
  ...
})

with .fail:

// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.get( "example.php", function() {
  alert( "success" );
})
  .done(function() {
    alert( "second success" );
  })
  .fail(function() {
    alert( "error" );
  })
  .always(function() {
    alert( "finished" );
  });

// Perform other work here ...

// Set another completion function for the request above
jqxhr.always(function() {
  alert( "second finished" );
});
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.