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();
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.
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.
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
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().
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.
Displaying node values from the XML file
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.