How do I make an AJAX request in JavaScript?
Richard W
richard w profile pic

In JavaScript, you can make AJAX (Asynchronous JavaScript and XML) requests using theXMLHttpRequest object or the newerfetch() function. These techniques allow you to send HTTP requests to a server and retrieve data asynchronously without refreshing the entire web page. Here's a step-by-step guide on how to make an AJAX request: Using XMLHttpRequest: 1. Create an XMLHttpRequest object: Start by creating an instance of theXMLHttpRequest object using thenew keyword. Here's an example:

1
2
3

   var xhr = new XMLHttpRequest();
   

2. Specify the request details: Configure the XMLHttpRequest object by specifying the HTTP method, URL, and any necessary request headers. Here's an example:

1
2
3
4
5

   var method = 'GET';
   var url = 'https://api.example.com/data';
   xhr.open(method, url);
   

In this code snippet,open() is used to specify the HTTP method (e.g., GET, POST, etc.) and the URL of the server endpoint. 3. Define the callback function: Create a function that will be executed when the AJAX request completes. This function will handle the response from the server. Here's an example:

1
2
3
4
5
6
7
8
9
10

   xhr.onload = function () {
     if (xhr.status === 200) {
       var response = xhr.responseText;
       console.log(response);
     } else {
       console.log('Request failed. Status: ' + xhr.status);
     }
   };
   

In this code snippet, theonload event is triggered when the request is completed. Inside the callback function, the response from the server is accessed usingxhr.responseText. You can perform further actions based on the status code (xhr.status) received from the server. 4. Send the request: Finally, send the AJAX request to the server using thesend() method. Here's an example:

1
2
3

   xhr.send();
   

This code snippet sends the request to the server. If the request is asynchronous, the code execution continues without waiting for the response. Using fetch(): 1. Make the fetch request: Use thefetch() function to make the AJAX request. Provide the URL as a parameter to fetch the data from the server. Here's an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

   var url = 'https://api.example.com/data';
   fetch(url)
     .then(function (response) {
       if (response.ok) {
         return response.text();
       }
       throw new Error('Request failed. Status: ' + response.status);
     })
     .then(function (data) {
       console.log(data);
     })
     .catch(function (error) {
       console.log(error);
     });
   

In this code snippet,fetch(url) sends a GET request to the specified URL. The response is handled using promises. Thethen() method is used to process the response and access the data. Thecatch() method is used to handle any errors that occur during the request. By following these steps, you can make an AJAX request in JavaScript using either theXMLHttpRequest object or thefetch() function. Choose the method that best fits your requirements and coding style. Remember to handle the response inside the appropriate callback or promise chain to process the server's response data.