Handling AJAX Errors and Success
Implement robust error handling mechanisms with .fail() and .always() callbacks, and process successful data retrieval with .done() for resilient applications.
Handling AJAX Errors and Success is a free jQuery Academy lesson on CoddyKit — lesson 2 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the jQuery Academy learning path, one of 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Handling Async Outcomes
When you make an AJAX request, it's an asynchronous operation. This means your code doesn't wait for the server's response; it continues executing other tasks.
To handle the server's reply (or lack thereof), jQuery provides special methods called callbacks. These functions run only when certain events occur, like success or failure.
When Everything Goes Right
The .done() callback is your go-to for handling successful AJAX requests. It executes when the server responds with a status code indicating success (typically 200-299).
- It receives the data returned from the server.
- It's the perfect place to update your UI with fresh information.
Displaying Successful Data
Let's fetch some data and display it when the request is successful. Notice how .done() is chained to the $.ajax() call.
$(document).ready(function() {
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts/1",
method: "GET"
})
.done(function(data) {
console.log("Success! Data received:");
console.log(data.title); // Access a property
$('body').append('<p>Post Title: ' + data.title + '</p>');
});
});When Things Go Wrong
But what if the server can't fulfill your request? That's where the .fail() callback comes in. It runs when the AJAX request encounters an error, such as a 404 (Not Found) or 500 (Server Error).
- It helps you inform the user or log issues.
- It receives details about the error.
Responding to Failures
Let's try to fetch from a non-existent URL. The .fail() callback will catch the error and log its details.
$(document).ready(function() {
$.ajax({
url: "https://jsonplaceholder.typicode.com/nonexistent", // This URL will fail
method: "GET"
})
.done(function(data) {
console.log("This won't run on error.");
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.log("Error! Status: " + textStatus);
console.log("HTTP Error: " + errorThrown);
$('body').append('<p>Error fetching data!</p>');
$('body').append('<p>Status: ' + textStatus + '</p>');
});
});Decoding Error Parameters
The .fail() callback provides three useful parameters to help you understand what went wrong:
jqXHR: The jQuery XMLHttpRequest object, offering low-level details.textStatus: A string describing the type of error (e.g., "timeout", "error", "abort").errorThrown: The HTTP status text (e.g., "Not Found" for a 404).
Use these to provide specific feedback to your users.
Always Running, No Matter What
Sometimes, you need to perform an action regardless of whether the AJAX request succeeded or failed. This is the job of the .always() callback.
- It always executes after either
.done()or.fail(). - Great for cleanup tasks like hiding a loading spinner or re-enabling a button.
Performing Cleanup
Let's add .always() to our previous example. We'll simulate a loading state and ensure it's removed whether the request succeeds or fails.
$(document).ready(function() {
$('body').append('<p id="status">Loading data...</p>'); // Simulate loading
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts/1", // Try changing to 'nonexistent' to see fail+always
method: "GET"
})
.done(function(data) {
console.log("Success! Data: " + data.title);
$('#status').text('Data loaded successfully!');
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.log("Failed! " + textStatus);
$('#status').text('Failed to load data!');
})
.always(function() {
console.log("Request finished (success or failure).");
// This could be where you hide a spinner or re-enable a button
$('#status').append(' (Finished)');
});
});Organizing Your Callbacks
jQuery's AJAX methods return a Promise-like object, allowing you to chain .done(), .fail(), and .always() methods directly.
This chaining makes your code cleaner and easier to read, clearly separating success, error, and final logic blocks.
Test Your Knowledge
Consider the following jQuery AJAX request:
$.ajax({
url: "/api/data",
method: "GET"
})
.done(function() {
console.log("A");
})
.fail(function() {
console.log("B");
})
.always(function() {
console.log("C");
});
If the server responds with a 404 Not Found error, what will be printed to the console?
Summarizing AJAX Handling
You've mastered the essential callbacks for robust AJAX handling:
.done(): For successful responses..fail(): For handling errors..always(): For actions that should run no matter what.
By using these, your applications can gracefully handle network interactions, providing a better experience for users even when things don't go as planned!
Frequently asked questions
Is the “Handling AJAX Errors and Success” lesson free?
Yes — the full text of “Handling AJAX Errors and Success” is free to read here on the web, and the jQuery Academy course includes 3 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the jQuery Academy course, upgrade to CoddyKit PRO.
What will I learn in “Handling AJAX Errors and Success”?
Implement robust error handling mechanisms with .fail() and .always() callbacks, and process successful data retrieval with .done() for resilient applications. You practise jQuery Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start jQuery Academy?
No prior experience is required. jQuery Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 3, so you can start here or from the beginning and move at your own pace.
How long does the “Handling AJAX Errors and Success” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this jQuery Academy lesson?
Yes. Every jQuery Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Configuring AJAX Requests Effectively
- Handling AJAX Errors and Success
- Cross-Domain AJAX (CORS/JSONP)