JS AJAX XML
In this page:
Reading responseXML from XMLHttpRequest
XMLHttpRequest automatically parses an XML response body into a Document object, available as xhr.responseXML, provided the server sent an XML-appropriate Content-Type header -- no manual parsing step required, unlike with fetch.
Note: Confirm the server is actually sending an XML content type if responseXML unexpectedly comes back null despite the body clearly being XML text.
Warning: responseXML remains null if the server's Content-Type header does not indicate XML, even if the raw response text is valid, well-formed XML.
Example: Reading responseXML from XMLHttpRequest
const xhr = new XMLHttpRequest();
xhr.onload = () => console.log(xhr.responseXML); // parsed automatically
xhr.open("GET", "data.xml");
xhr.send();
Parsing XML with fetch and DOMParser
fetch does not have an equivalent to responseXML -- an XML response must be read as plain text with response.text(), then parsed manually into a Document using new DOMParser().parseFromString(text, 'text/xml').
Note: Always specify 'text/xml' (or 'application/xml') as the MIME type argument to parseFromString, so DOMParser knows to parse it as XML rather than HTML.
Warning: DOMParser inserts a special <parsererror> element into the resulting document rather than throwing a catchable exception on malformed XML -- check for it explicitly.
Example: Parsing XML with fetch and DOMParser
fetch("data.xml")
.then(response => response.text())
.then(text => new DOMParser().parseFromString(text, "text/xml"))
.then(doc => console.log(doc));
Navigating a Parsed XML Document
Once parsed (via either responseXML or DOMParser), an XML response behaves like any other DOM document -- querySelector(), querySelectorAll(), and getElementsByTagName() all work identically to how they work on an HTML page.
Note: Use the same DOM traversal methods you already know from HTML pages when working with a parsed XML document -- no separate XML-specific API to learn.
Warning: XML tag names are case-sensitive, unlike HTML, so querySelector("Title") and querySelector("title") can match entirely different elements in an XML document.
Example: Navigating a Parsed XML Document
const xmlText = "<root><item>Test</item></root>";
const doc = new DOMParser().parseFromString(xmlText, "text/xml");
console.log(doc.querySelector("item").textContent);
Comparing XML and JSON Responses
Converting an existing XML-based endpoint's response to JSON is often worth doing for new features, since JSON parses into plain JavaScript objects/arrays automatically, requiring none of the manual DOM-style navigation XML needs -- but reading existing XML endpoints remains a real, occasional necessity.
Note: For a brand-new endpoint you control, prefer JSON; reserve XML-handling code specifically for endpoints where XML is already the established format.
Warning: Converting an existing, working XML-based system to JSON is a larger undertaking than it might first appear, especially if other consumers of that XML endpoint cannot be changed at the same time.
Example: Comparing XML and JSON Responses
const doc = new DOMParser().parseFromString("<root><item>1</item></root>", "text/xml");
console.log(doc.getElementsByTagName("item")[0].textContent);
console.log(JSON.parse('{"item": 1}').item);
A Practical XML AJAX Example
Combining the pieces: fetching an RSS-style XML feed, parsing it with DOMParser, and looping over its repeated <item> elements to build a simple list of headlines -- a realistic, complete example of consuming an XML-based AJAX endpoint end to end.
Note: Build and test XML-parsing code incrementally: confirm the fetch and parse succeed first, then add the loop and rendering logic afterward.
Warning: An RSS or XML feed from an external source is outside your control and can occasionally change structure -- defensive checks (confirming an expected element exists before reading it) help avoid a broken page from an unexpected format change.
Example: A Practical XML AJAX Example
fetch("feed.xml")
.then(r => r.text())
.then(text => {
const doc = new DOMParser().parseFromString(text, "text/xml");
doc.querySelectorAll("item").forEach(item => console.log(item.textContent));
});
- Trying to use response.json() on an XML response, which fails since the body is not valid JSON -- XML responses must be read as text and parsed separately.
- Forgetting that responseXML (on XMLHttpRequest) is only populated automatically if the server sends the correct Content-Type header for XML.
- Not checking for a parser error in the resulting document, which DOMParser inserts as a special element rather than throwing a catchable exception.
- XMLHttpRequest automatically parses an XML response into responseXML if the server's Content-Type header indicates XML.
- For fetch, an XML response must be read with response.text() and then parsed manually using the built-in DOMParser.
- Once parsed, an XML response can be navigated with the same DOM methods (querySelector, getElementsByTagName) used on an HTML document.
XMLHttpRequest.responseXML and the DOMParser API are both supported in every modern browser.
Chapter Quiz — Complete all 26 topics to unlock
0/26 topics done
Complete these topics first:
- JS JSON
- JS Regular Expressions
- JS Fetch API
- JS LocalStorage and SessionStorage
- JS Cookies
- JS setTimeout and setInterval
- JS Event Loop
- JS Web Workers
- JS Service Workers
- JS AJAX
- JS AJAX Intro
- JS AJAX XMLHttp
- JS AJAX Request
- JS AJAX Response
- JS AJAX XML
- JS AJAX PHP
- JS AJAX Database
- JS JSONP
- JS RegExp Flags
- JS RegExp Classes
- JS RegExp Metachars
- JS RegExp Assertions
- JS RegExp Groups
- JS RegExp Quantifiers
- JS JSON HTML
- JS JSON vs XML