1️⃣1️⃣ 📚 XML DOM References & Definitions
Estimated reading: 3 minutes 24 views

🌐 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 XMLHttpRequest is 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

MethodDescription
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

PropertyDescription
readyStateStatus (0–4) of the request
statusHTTP response code (e.g., 200, 404)
responseTextResponse as string (default for text/JSON)
responseXMLParsed XML Document object
onreadystatechangeEvent 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

ValueStateDescription
0UNSENTopen() not called yet
1OPENEDopen() has been called
2HEADERS_RECEIVEDResponse headers received
3LOADINGReceiving data
4DONERequest finished and response ready

✅ Best Practices for XMLHttpRequest

  • ✔️ Always check readyState === 4 && status === 200
  • ✔️ Use responseXML for structured XML responses
  • ✔️ Set appropriate headers for POST/PUT (Content-Type)
  • ❌ Don’t use synchronous mode (open(..., false))—it blocks the UI
  • ❌ Avoid using XMLHttpRequest for modern apps—prefer fetch() 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(), and onreadystatechange to control the request
  • Parse responseXML for XML responses
  • Check readyState and status for 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 :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

DOM XMLHttpRequest

Or Copy Link

CONTENTS
Scroll to Top