1️⃣ 📘 XML Home
Estimated reading: 4 minutes 702 views

XML HttpRequest – Load & Send XML with JavaScript

Introduction – Why Learn XML HttpRequest?

XMLHttpRequest is a JavaScript API used to send and retrieve data asynchronously without reloading the web page. Although it supports all data formats, it’s historically named for XML and is still used to load XML documents, submit XML payloads, or fetch XML-based APIs dynamically.

In this guide, you’ll learn:

  • What XMLHttpRequest is and how it works
  • How to load and parse XML from a server
  • How to send XML data to a backend
  • Real-world use cases with code examples

What Is XMLHttpRequest?

XMLHttpRequest (XHR) is an object built into modern browsers that enables AJAX-style data loading. It can:

  • Fetch XML from a URL
  • Parse and display XML response
  • Send XML data as POST or PUT

Supported in all major browsers, including Chrome, Firefox, Safari, and Edge.


Load XML with XMLHttpRequest (GET Method)

Example: Fetch and Display XML

<script>
  var xhr = new XMLHttpRequest();
  xhr.open("GET", "books.xml", true);
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
      var xml = xhr.responseXML;
      var titles = xml.getElementsByTagName("title");
      let output = "";
      for (var i = 0; i < titles.length; i++) {
        output += "<p>" + titles[i].textContent + "</p>";
      }
      document.getElementById("display").innerHTML = output;
    }
  };
  xhr.send();
</script>
<div id="display"></div>

books.xml Example:

<library>
  <book>
    <title>Learn XML</title>
  </book>
</library>

Send XML Data to Server (POST Method)

You can send structured XML to the server using POST.

Example: POST XML Payload

var xhr = new XMLHttpRequest();
xhr.open("POST", "submit.php", true);
xhr.setRequestHeader("Content-Type", "application/xml");

var xmlData = `
<user>
  <name>Jane Doe</name>
  <email>jane@example.com</email>
</user>
`;

xhr.send(xmlData);

The server must be configured to parse XML correctly (e.g., using PHP’s simplexml_load_string() or Python’s ElementTree).


XMLHttpRequest Object – Key Properties & Methods

Property/MethodDescription
open(method, url)Initializes request with HTTP method & URL
send(data)Sends request to server
responseXMLParsed XML DOM from response
onreadystatechangeEvent triggered on state change
readyStateTracks current state of request (0–4)
statusHTTP response status (200 = OK, 404 = Not Found)

readyState Values Explained

ValueMeaning
0UNSENT – request not initialized
1OPENED – server connection established
2HEADERS_RECEIVED – request received
3LOADING – processing request
4DONE – request complete

Check for readyState === 4 && status === 200 before processing the response.


Best Practices for XML HttpRequest

  • ✔️ Always check readyState and status before accessing the response
  • ✔️ Use responseXML for parsing XML automatically
  • ✔️ Set correct Content-Type when sending XML (application/xml)
  • ✔️ Escape special XML characters when building strings
  • Avoid blocking requests (open(..., false)) — always use async

Summary – Recap & Next Steps

XMLHttpRequest is a powerful tool to load and transmit XML data in web apps without full page reloads. It remains relevant even alongside fetch() for XML-based workflows.

Key Takeaways:

  • Use GET to fetch XML, POST to send XML data
  • Access XML response with responseXML
  • Always monitor readyState and status before processing

Real-world relevance: XHR is used in dashboards, live data feeds, XML APIs, and client-side data submission in legacy systems.


FAQs – XML HttpRequest

Is XMLHttpRequest only for XML?
No. It supports text, JSON, HTML, and XML—but was originally designed for XML.

What is the difference between responseText and responseXML?
responseText returns a string; responseXML returns a parsed XML DOM object.

Do modern applications still use XMLHttpRequest?
While fetch() is newer, XHR is still widely supported and useful for XML-heavy systems.

What is the correct Content-Type when sending XML?
Use application/xml or text/xml.

Can I use XMLHttpRequest synchronously?
Technically yes, but it’s discouraged as it blocks the browser UI thread.


Share Now :
Share

XML HttpRequest

Or Copy Link

CONTENTS
Scroll to Top