jQuery .ajax() method


The .ajax() method in jQuery provides a powerful and flexible way to perform asynchronous HTTP requests. It allows you to send and receive data from a server without refreshing the entire page. This method supports a wide range of configuration options, giving you complete control over your AJAX requests.

Syntax

$.ajax({ url: "URL", type: "GET/POST/PUT/DELETE", data: { key: "value" }, dataType: "json", success: function(response) { // Handle successful response }, error: function(jqXHR, textStatus, errorThrown) { // Handle errors }, complete: function(jqXHR, textStatus) { // Optional callback executed after success or error }, timeout: 30000, // Optional timeout in milliseconds headers: { "Custom-Header": "value" } // Optional headers });

Parameters

  • url: The URL to which the request is sent. This can be an absolute URL or a relative path.
  • type: The HTTP method to use (e.g., GET, POST, PUT, DELETE). Defaults to GET.
  • data: Data to be sent to the server. This can be an object, array, or string. For POST requests, this data is sent in the request body.
  • dataType: The type of data expected from the server. Common values include json, xml, html, text. jQuery will automatically parse the response based on this setting.
  • success: A callback function executed if the request succeeds. It receives the data returned from the server and the status text.
  • error: A callback function executed if the request fails. It receives the XMLHttpRequest object, a text status, and an optional exception object.
  • complete: A callback function executed when the request completes, regardless of success or failure. It receives the XMLHttpRequest object and the status text.
  • timeout: Specifies a timeout period in milliseconds for the request. If the request takes longer than this time, it will be aborted.
  • headers: An object of additional headers to send with the request.

Example of a Basic GET Request

$.ajax({ url: "https://api.example.com/data", type: "GET", dataType: "json", success: function(response) { console.log("Data received:", response); }, error: function(jqXHR, textStatus, errorThrown) { console.error("Error:", textStatus, errorThrown); } });

Example of a POST Request with Data

$.ajax({ url: "https://api.example.com/submit", type: "POST", data: { name: "John", age: 30 }, dataType: "json", success: function(response) { console.log("Server response:", response); }, error: function(jqXHR, textStatus, errorThrown) { console.error("Error:", textStatus, errorThrown); } });

Example of Handling XML Responses

$.ajax({ url: "https://api.example.com/data.xml", type: "GET", dataType: "xml", success: function(response) { $(response).find("item").each(function() { var name = $(this).find("name").text(); $("#list").append("<li>" + name + "</li>"); }); }, error: function(jqXHR, textStatus, errorThrown) { console.error("Error:", textStatus, errorThrown); } });

Example of Setting Request Headers

$.ajax({ url: "https://api.example.com/data", type: "GET", headers: { "Authorization": "Bearer YOUR_ACCESS_TOKEN", "Custom-Header": "value" }, success: function(response) { console.log("Data received:", response); }, error: function(jqXHR, textStatus, errorThrown) { console.error("Error:", textStatus, errorThrown); } });

Example of Using .ajax() with Timeout and Complete Callback

$.ajax({ url: "https://api.example.com/data", type: "GET", dataType: "json", timeout: 5000, // 5 seconds timeout success: function(response) { console.log("Data received:", response); }, error: function(jqXHR, textStatus, errorThrown) { console.error("Error:", textStatus, errorThrown); }, complete: function(jqXHR, textStatus) { console.log("Request complete with status:", textStatus); } });

Practical Use Cases

  1. Loading Data Dynamically

    • Fetching data from an API and updating the page without reloading.
  2. Form Submission

    • Submitting form data to the server and handling responses without refreshing the page.
  3. Error Handling

    • Providing user feedback or logging errors if an AJAX request fails.
  4. Interacting with RESTful APIs

    • Sending GET, POST, PUT, and DELETE requests to RESTful APIs to interact with resources.