AJAX XML Response Handling
Estimated study time: 13 minutes.
Once an AJAX request completes, the server's XML reply needs to be turned into something your JavaScript can actually use. That's what response handling is about.
Accessing the Raw Response
An XHR object exposes the response in two forms: responseText (a plain string) and responseXML (already parsed into a DOM document, as long as the server sent the correct content type).
xhr.onload = function() {
let xmlDoc = xhr.responseXML;
console.log(xmlDoc);
};
Reading Values from the Response
let names = xmlDoc.getElementsByTagName("name");
for (let i = 0; i < names.length; i++) {
console.log(names[i].textContent);
}
Handling Errors Gracefully
xhr.onerror = function() {
console.log("Request failed.");
};
xhr.onload = function() {
if (xhr.status !== 200) {
console.log("Server returned an error: " + xhr.status);
return;
}
// process xhr.responseXML here
};
Content-Type Matters
If the server doesn't send the response with an XML content type (like text/xml or application/xml), responseXML will be null even if the body looks like XML. In that case, you'd need to parse responseText manually with a DOMParser.
💡 Tip: If
responseXML keeps coming back null, check the server's response headers first — it's almost always a content-type mismatch, not a parsing bug.