XMLHttpRequest to Read Data from an XML File

XMLHttpRequest can request an XML document and expose the parsed result through responseXML. For browser code, use an asynchronous request so the page remains responsive while the XML file is being loaded.

const request = new XMLHttpRequest();
request.open('GET', '../php_tutorial/file-xml-demo.xml', true);
request.addEventListener('load', () => {
  const xmlDocument = request.responseXML;
  if (!xmlDocument) {
    console.error('The response could not be parsed as XML.');
    return;
  }
  console.log(xmlDocument);
});
request.send();
Table of Contents

How XMLHttpRequest Loads XML Top ↑

Create the request object, open a GET request, register the result handler, and call send(). The original tutorial checked for ActiveX as a fallback; modern browsers support XMLHttpRequest directly.

Related TutorialsXML basicsPHP & XML

XMLHttpRequest is also historically associated with Ajax, where a page exchanges data with a server without doing a full page reload. See the original PHP Ajax section.

Sample XML File Top ↑

The examples in this cluster use the same sample XML document as the original tutorial:

https://www.plus2net.com/php_tutorial/file-xml-demo.xml

Reading responseXML Top ↑

const request = new XMLHttpRequest();
request.open('GET', '../php_tutorial/file-xml-demo.xml', true);
request.addEventListener('load', () => {
  if (request.status >= 200 && request.status < 300) {
    const xmlDocument = request.responseXML;
    if (xmlDocument) {
      const names = xmlDocument.getElementsByTagName('name');
      console.log(names.length);
    }
  }
});
request.addEventListener('error', () => console.error('XML request failed.'));
request.send();

When the server returns valid XML with an XML content type, responseXML is a parsed XML Document. You can then use familiar DOM methods such as getElementsByTagName().

Legacy Synchronous / ActiveX Pattern Top ↑

The original page used the following compatibility pattern. It is retained here for understanding older code, but it should not be the starting point for new browser code:

// Historical example
if (window.XMLHttpRequest) {
  my_xml = new XMLHttpRequest();
} else {
  my_xml = new ActiveXObject('Microsoft.XMLHTTP');
}
my_xml.open('GET', '../php_tutorial/file-xml-demo.xml', false);
my_xml.send();

The ActiveX fallback belongs to old Internet Explorer code. A synchronous XHR on the main browser thread can block interaction while the network request is running, so the working examples in this modernization use asynchronous requests.

Next Step Top ↑

Displaying node values from the XML file

XML




Subscribe to our YouTube Channel here



plus2net.com










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer