How to use the jQuery.ajax() method

In jQuery, the ajax() method makes an asynchronous HTTP request to the server. This request helps fetch data from the server and update the DOM without refreshing or reloading the page.

Syntax

$.ajax({
   key: value,
   key: value,
   ... 
});

Parameters

The parameters of ajax() are one or more key-value pairs. Some of the possible parameters are as follows:

  1. url: Specifies the URL at which the request will be made.
  2. type: Specifies the type of request; possible values are GET, POST, PUT, and DELETE.
  3. xhr: Creates an instance of XMLHTTPRequest().
  4. contentType: Specifies the content type when sending data to the server.
  5. dataType: The expected data type of the response.
  6. processData: A Boolean value that specifies whether to process the data sent with the request into a query string.
  7. async: Specifies whether the request should be made asynchronously or not.
  8. username: Specifies the username to be used in the HTTP Access Authentication request.
  9. password: Specifies the password to be used in the HTTP Access Authentication request.
  10. data: The data sent to the server.
  11. success: A function to execute when the request is successfully completed.
  12. error: A function to execute when the request fails.
  13. complete: A function to execute when the request is completed.
  14. beforeSend: A function to execute before the request is made.
  15. dataFilter: A function to handle the raw response data of the XMLHttpRequest.
  16. traditional: A Boolean value that specifies whether to use the traditional style of param serialization.
  17. timeout: Specifies the local timeout of the request in milliseconds.
  18. context: Specifies the this value for all Ajax callback functions.

Example

Explanation

We make a GET request on https://reqres.in/api/products to fetch product details.

If the request is successful, we iterate over the response and add them into the DOM. If the request fails, we append the error into the DOM.

Free Resources