Making AJAX Requests in JavaScript
AJAX (Asynchronous JavaScript and XML) allows web applications to send and receive data asynchronously without refreshing the page. The primary method for making AJAX requests in JavaScript is through the XMLHttpRequest (XHR) object.
1. Creating an XMLHttpRequest Object
To initiate an AJAX request, create an instance of the XMLHttpRequest object:
var xhr = new XMLHttpRequest();2. Configuring the Request
Use the open method to configure the request. It requires three parameters:
- HTTP Method: The HTTP method (GET, POST, PUT, DELETE).
- URL: The endpoint URL to which the request is sent.
- Asynchronous: A boolean value indicating whether to perform the request asynchronously (true) or synchronously (false).
Example of configuring a GET request:
xhr.open('GET', 'https://api.example.com/data', true);3. Sending the Request
Use the send method to send the request:
xhr.send();4. Handling the Response
Use the onreadystatechange event to handle the response from the server:
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
console.log(JSON.parse(xhr.responseText));
} else {
console.error('Error:', xhr.statusText);
}
}
};5. HTTP Methods with XMLHttpRequest
Here’s how to use different HTTP methods with XMLHttpRequest:
GET Request
var xhrGet = new XMLHttpRequest();
xhrGet.open('GET', 'https://api.example.com/data', true);
xhrGet.onreadystatechange = function() {
if (xhrGet.readyState === XMLHttpRequest.DONE) {
if (xhrGet.status === 200) {
console.log(JSON.parse(xhrGet.responseText));
}
}
};
xhrGet.send();POST Request
var xhrPost = new XMLHttpRequest();
xhrPost.open('POST', 'https://api.example.com/data', true);
xhrPost.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
xhrPost.onreadystatechange = function() {
if (xhrPost.readyState === XMLHttpRequest.DONE) {
console.log(xhrPost.responseText);
}
};
xhrPost.send(JSON.stringify({ key: 'value' }));PUT Request
var xhrPut = new XMLHttpRequest();
xhrPut.open('PUT', 'https://api.example.com/data/1', true);
xhrPut.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
xhrPut.onreadystatechange = function() {
if (xhrPut.readyState === XMLHttpRequest.DONE) {
console.log(xhrPut.responseText);
}
};
xhrPut.send(JSON.stringify({ key: 'new_value' }));DELETE Request
var xhrDelete = new XMLHttpRequest();
xhrDelete.open('DELETE', 'https://api.example.com/data/1', true);
xhrDelete.onreadystatechange = function() {
if (xhrDelete.readyState === XMLHttpRequest.DONE) {
console.log(xhrDelete.responseText);
}
};
xhrDelete.send();6. Conclusion
Using XMLHttpRequest allows you to make HTTP requests in JavaScript efficiently. Whether you're fetching data from an API or sending data to a server, understanding how to use XHR is crucial for modern web development.