🌐 DOM XMLHttpRequest – Send and Receive XML or Data Asynchronously
🧲 Introduction – Why Learn About XMLHttpRequest?
The XMLHttpRequest object is a core part of the DOM API that enables asynchronous communication with web servers. It allows JavaScript to send HTTP requests and receive responses without reloading the page. Despite modern alternatives like fetch(), XMLHttpRequest remains widely used—especially in legacy systems, XML-based applications, and AJAX integrations.
🎯 In this guide, you’ll learn:
- What
XMLHttpRequestis and how it works - How to make GET and POST requests using it
- How to handle XML responses in the DOM
- Real-world use cases and best practices
📘 What Is XMLHttpRequest?
XMLHttpRequest is a built-in JavaScript object that provides methods to:
- Send HTTP/HTTPS requests
- Receive responses (HTML, XML, JSON, plain text)
- Work asynchronously or synchronously (non-blocking/blocking)
✅ It forms the foundation of AJAX (Asynchronous JavaScript and XML).
🧾 Basic Syntax
const xhr = new XMLHttpRequest();
xhr.open("GET", "data.xml", true); // method, URL, async
xhr.send();
🔁 Common Methods
| Method | Description |
|---|---|
open(method, url, async) | Initializes the request |
send(body) | Sends the request (use null for GET) |
setRequestHeader() | Sets custom HTTP headers (e.g. content type) |
abort() | Cancels an active request |
🧩 Key Properties
| Property | Description |
|---|---|
readyState | Status (0–4) of the request |
status | HTTP response code (e.g., 200, 404) |
responseText | Response as string (default for text/JSON) |
responseXML | Parsed XML Document object |
onreadystatechange | Event handler called when readyState changes |
🔍 Example – Load XML and Access with DOM
const xhr = new XMLHttpRequest();
xhr.open("GET", "books.xml", true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
const xmlDoc = xhr.responseXML;
const titles = xmlDoc.getElementsByTagName("title");
for (let i = 0; i < titles.length; i++) {
console.log(titles[i].textContent);
}
}
};
xhr.send();
✅ This fetches books.xml and prints all <title> elements.
🧪 Example – POST JSON Data
const xhr = new XMLHttpRequest();
xhr.open("POST", "/api/submit", true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log("Response:", xhr.responseText);
}
};
const data = JSON.stringify({ name: "John", age: 30 });
xhr.send(data);
📶 readyState Values
| Value | State | Description |
|---|---|---|
0 | UNSENT | open() not called yet |
1 | OPENED | open() has been called |
2 | HEADERS_RECEIVED | Response headers received |
3 | LOADING | Receiving data |
4 | DONE | Request finished and response ready |
✅ Best Practices for XMLHttpRequest
- ✔️ Always check
readyState === 4 && status === 200 - ✔️ Use
responseXMLfor structured XML responses - ✔️ Set appropriate headers for POST/PUT (
Content-Type) - ❌ Don’t use synchronous mode (
open(..., false))—it blocks the UI - ❌ Avoid using
XMLHttpRequestfor modern apps—preferfetch()unless XML is needed
📌 Summary – Recap & Next Steps
XMLHttpRequest enables web pages to fetch data asynchronously, powering dynamic UIs, AJAX functionality, and real-time data rendering. It’s particularly useful when dealing with XML data or legacy APIs.
🔍 Key Takeaways:
- Use
open(),send(), andonreadystatechangeto control the request - Parse
responseXMLfor XML responses - Check
readyStateandstatusfor successful loads
⚙️ Real-world relevance: Used in AJAX applications, XML data parsing, dynamic interfaces, form submissions, and legacy enterprise systems.
❓ FAQs – DOM XMLHttpRequest
❓ Is XMLHttpRequest still used in 2025?
✅ Yes, especially in legacy codebases and XML-heavy APIs.
❓ What’s the difference between responseText and responseXML?
✅ responseText is a string; responseXML is a parsed Document.
❓ Can I send custom headers?
✅ Yes, using setRequestHeader().
❓ Does XMLHttpRequest support JSON?
✅ Yes. You can send/receive JSON using proper headers and JSON.parse().
❓ Should I use XMLHttpRequest or fetch()?
✅ Use fetch() for modern projects; XMLHttpRequest is better for XML workflows or backward compatibility.
Share Now :
