When making an AJAX request with jQuery, you can handle success and error responses using the .done()
and .fail()
methods respectively. Here is an example:
$.ajax({
url: "example.com/data",
method: "GET"
})
.done(function(response) {
// Handle success response
console.log(response);
})
.fail(function(jqXHR, textStatus, errorThrown) {
// Handle error response
console.log(textStatus);
})
In the above example, the .done()
method is used to handle a successful AJAX response, and the .fail()
method is used to handle any error that occurs during the request.
You can also use the .always()
method to execute a function regardless of whether the request was successful or resulted in an error:
$.ajax({
url: "example.com/data",
method: "GET"
})
.done(function(response) {
// Handle success response
console.log(response);
})
.fail(function(jqXHR, textStatus, errorThrown) {
// Handle error response
console.log(textStatus);
})
.always(function() {
// This will be executed regardless of success or failure
});
Additionally, you can use the .then()
method to handle both success and error responses in a more concise way:
$.ajax({
url: "example.com/data",
method: "GET"
})
.then(
function(response) {
// Handle success response
console.log(response);
},
function(jqXHR, textStatus, errorThrown) {
// Handle error response
console.log(textStatus);
}
);
In the .then()
method, you pass two separate functions, one to handle the success response, and the other to handle the error response.