AJAX XML Example
Estimated study time: 11 minutes.
Let's put the pieces together with a complete example: fetching a small XML file with student records and displaying it on the page.
The XML File (students.xml)
<students>
<student>
<name>Ananya Sharma</name>
<course>Data Analytics</course>
</student>
<student>
<name>Rohan Verma</name>
<course>Web Development</course>
</student>
</students>
The AJAX Request
let xhr = new XMLHttpRequest();
xhr.open("GET", "students.xml", true);
xhr.onload = function() {
if (xhr.status === 200) {
let xmlDoc = xhr.responseXML;
let students = xmlDoc.getElementsByTagName("student");
let output = "";
for (let i = 0; i < students.length; i++) {
let name = students[i].getElementsByTagName("name")[0].textContent;
let course = students[i].getElementsByTagName("course")[0].textContent;
output += name + " – " + course + "<br>";
}
document.getElementById("result").innerHTML = output;
}
};
xhr.send();
What's Happening
- The browser requests
students.xmlin the background. - Once loaded, the response is parsed automatically into
responseXML. - JavaScript loops through each
<student>node and builds an HTML string. - The page updates instantly — no reload required.
💡 Tip: This exact pattern — request, parse, loop, render — is the backbone of almost every AJAX-driven feature, whether the data comes back as XML or JSON.