To use deferred objects and promises with AJAX requests in jQuery, you can follow these steps:
$.Deferred()
function.var deferred = $.Deferred();
$.ajax()
function and pass the deferred
object as the deferred
option.$.ajax({
url: "example.php",
method: "GET",
deferred: deferred
});
done()
, fail()
, and always()
methods to the deferred
object to handle the success, error, and completion of the AJAX request.deferred.done(function(response) {
console.log("Success: ", response);
}).fail(function(error) {
console.log("Error: ", error);
}).always(function() {
console.log("Completed.");
});
deferred
object based on the success or failure of the AJAX request.deferred.resolve("Data received successfully!");
// or
deferred.reject("Error occurred during request.");
By using deferred.resolve()
or deferred.reject()
, you can control when the success or error handlers are executed.
then()
method to handle both success and error cases in one function.deferred.then(function(response) {
console.log("Success: ", response);
}, function(error) {
console.log("Error: ", error);
});
This approach allows you to handle the success and error cases separately within the same function.
Note: The done()
, fail()
, and always()
methods can also be used directly on the $.ajax()
object instead of the deferred
object if you don't need to create a separate deferred
object explicitly.