
AJAX XMLHttpRequest
The XMLHttpRequest (XHR) is an API in web development that provides the ability to make HTTP or HTTPS requests to the server from a web page using JavaScript. It is a core component of AJAX (Asynchronous JavaScript and XML), allowing web applications to send and receive data from the server asynchronously without requiring a full page reload. The XHR object is widely used, but newer APIs like the Fetch API have also gained popularity due to their improved design and features.
Here’s an overview of how to use the XMLHttpRequest object in AJAX:
- Create an XMLHttpRequest Object: To use AJAX with XMLHttpRequest, you first need to create an instance of the XMLHttpRequest object. In modern JavaScript, this can be done as follows:
var xhr = new XMLHttpRequest();
- Set up the Request: Configure the XHR object by specifying the HTTP method (GET, POST, PUT, DELETE), the URL to which the request will be sent, and any optional parameters or headers. For example:
var method = 'GET'; // or 'POST', 'PUT', 'DELETE'
var url = 'https://example.com/api/data';
xhr.open(method, url, true);
- Set Request Headers (Optional): You can set additional headers, such as content type or authentication information, if required:
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Authorization', 'Bearer YOUR_ACCESS_TOKEN');
- Handle the Response: Set up an event listener to handle the server’s response when it is received:
xhr.onload = function () {
if (xhr.status >= 200 && xhr.status < 300) {
// Request was successful, handle the response data here
var responseData = JSON.parse(xhr.responseText);
// Update the DOM or perform other actions based on the response
} else {
// Request failed, handle errors here
console.error('Request failed with status:', xhr.status);
}
};
- Send the Request: Finally, send the HTTP request to the server:
xhr.send();
- Asynchronous Nature: By default, the XHR request is asynchronous (true in the
xhr.open()
method above). This means that the request will be sent in the background, and the JavaScript execution will continue without waiting for the response. When the response is received, theonload
event handler will be triggered to process the data. - Error Handling: You can also set up an
onerror
event handler to handle errors if the request fails to reach the server or encounters other issues.
Note: AJAX requests are subject to the same-origin policy, meaning that the request can only be made to the same domain from which the web page originated unless CORS (Cross-Origin Resource Sharing) headers are correctly set on the server-side.
As mentioned earlier, while XMLHttpRequest is still commonly used, newer APIs like the Fetch API provide a more modern and user-friendly way to perform similar tasks, and they are often preferred in modern web development.