How to use deferred objects and promises with AJAX requests in jQuery?

To use deferred objects and promises with AJAX requests in jQuery, you can follow these steps:

  1. Create a new deferred object using the $.Deferred() function.
var deferred = $.Deferred();
  1. Make an AJAX request using the $.ajax() function and pass the deferred object as the deferred option.
$.ajax({ url: "example.php", method: "GET", deferred: deferred });
  1. Chain the 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."); });
  1. Resolve or reject the 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.

  1. Alternatively, you can use the 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.