XMLHttpRequest for AJAX Calls
The XMLHttpRequest (XHR) object is a core feature of JavaScript that allows you to send and receive data asynchronously from a server without refreshing the web page. It forms the foundation of AJAX (Asynchronous JavaScript and XML), enabling dynamic and interactive web applications.
1. What is XMLHttpRequest?
XMLHttpRequest is an API in JavaScript that facilitates communication with servers through HTTP requests. It supports:
- Data retrieval without page reloads.
- Handling various formats like JSON, XML, HTML, and text.
- Both synchronous and asynchronous operations (though synchronous mode is deprecated for most use cases).
2. Creating an XMLHttpRequest Object
To use XHR, create an instance of the XMLHttpRequest
object:
const xhr = new XMLHttpRequest();
3. Steps to Make an XHR Call
- Create the XHR Object:
const xhr = new XMLHttpRequest();
-
Initialize the Request:
Use the
open()
method to define the HTTP method, URL, and whether the call is asynchronous.
xhr.open("GET", "https://api.example.com/data", true);
-
Set Up a Callback for the Response:
Use the
onreadystatechange
event or theload
event.
xhr.onload = function () {
if (xhr.status === 200) {
console.log("Response:", xhr.responseText);
} else {
console.error("Error:", xhr.status, xhr.statusText);
}
};
- Send the Request:
xhr.send();
4. Complete Example: GET Request
const xhr = new XMLHttpRequest();
xhr.open("GET", "https://jsonplaceholder.typicode.com/posts", true);
xhr.onload = function () {
if (xhr.status === 200) {
console.log("Data retrieved:", JSON.parse(xhr.responseText));
} else {
console.error("Failed to fetch data. Status:", xhr.status);
}
};
xhr.onerror = function () {
console.error("Request failed due to a network error.");
};
xhr.send();
5. Sending Data with POST Requests
XHR allows sending data to the server using POST.
Example:
const xhr = new XMLHttpRequest();
xhr.open("POST", "https://jsonplaceholder.typicode.com/posts", true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onload = function () {
if (xhr.status === 201) {
console.log("Data saved:", JSON.parse(xhr.responseText));
} else {
console.error("Error:", xhr.status);
}
};
const data = JSON.stringify({
title: "foo",
body: "bar",
userId: 1
});
xhr.send(data);
6. Properties and Methods of XHR
Key Properties:
-
readyState
: Represents the state of the request (0 to 4).-
0
: UNSENT -
1
: OPENED -
2
: HEADERS_RECEIVED -
3
: LOADING -
4
: DONE
-
status
: HTTP status code (e.g., 200 for success, 404 for not found).responseText
: The response body as a text string.responseXML
: The response body as XML data (if applicable).
Key Methods:
-
open(method, url, async)
: Initializes the request. -
send(data)
: Sends the request to the server. -
setRequestHeader(header, value)
: Sets custom headers. -
abort()
: Cancels the request.
7. Handling Response States
You can use the onreadystatechange
event to monitor the progress of an XHR request.
Example:
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log("Data:", xhr.responseText);
}
};
8. Advantages of Using XHR
- Asynchronous Communication: Avoids blocking the main thread.
- Cross-Browser Support: Works across modern and older browsers.
- Flexible Data Formats: Supports JSON, XML, HTML, and plain text.
9. Limitations of XHR
-
Verbose Syntax: Requires more code compared to modern APIs like
fetch
. - Callback Hell: Complex requests can lead to deeply nested callbacks.
- Limited Modern Features: Lacks features like Promises or async/await.
10. Modern Alternatives: Fetch API
While XHR is still widely supported, the Fetch API offers a modern, promise-based approach to making HTTP requests.
Fetch Example:
fetch("https://jsonplaceholder.typicode.com/posts")
.then(response => response.json())
.then(data => console.log("Data:", data))
.catch(error => console.error("Error:", error));
11. Conclusion
XMLHttpRequest is a reliable and well-supported tool for making AJAX calls, but modern APIs like fetch
or libraries such as Axios are generally preferred for their simplicity and enhanced features. However, understanding XHR is essential for maintaining legacy code and gaining a deeper knowledge of how asynchronous communication works in JavaScript.
Hi, I'm Abhay Singh Kathayat!
I am a full-stack developer with expertise in both front-end and back-end technologies. I work with a variety of programming languages and frameworks to build efficient, scalable, and user-friendly applications.
Feel free to reach out to me at my business email: kaashshorts28@gmail.com.
Top comments (0)