-
Hajipur, Bihar, 844101
Although JSON has become the preferred format for data exchange, XML is still widely used in web applications, APIs, and legacy systems. AJAX can fetch XML data from a server and process it dynamically, allowing web pages to update content without reloading.
This tutorial explains how to use AJAX with XML, parse XML responses, and display the data on a web page dynamically.
XML (eXtensible Markup Language) is a structured format for storing and transporting data. Unlike HTML, XML does not define how data should look, but organizes data hierarchically.
Example XML: students.xml
<students>
<student id="1">
<name>Riya Sharma</name>
<age>20</age>
<course>Web Development</course>
</student>
<student id="2">
<name>Ananya Singh</name>
<age>22</age>
<course>Data Science</course>
</student>
<student id="3">
<name>Meera Patel</name>
<age>21</age>
<course>UI/UX Design</course>
</student>
</students>
HTML File: index.html
<!DOCTYPE html>
<html>
<head>
<title>AJAX XML Example</title>
<script>
function fetchXML() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "students.xml", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var xmlDoc = xhr.responseXML;
displayStudents(xmlDoc);
}
};
xhr.send();
}
function displayStudents(xml) {
var table = "<table border='1'><tr><th>ID</th><th>Name</th><th>Age</th><th>Course</th></tr>";
var students = xml.getElementsByTagName("student");
for (var i = 0; i < students.length; i++) {
var id = students[i].getAttribute("id");
var name = students[i].getElementsByTagName("name")[0].childNodes[0].nodeValue;
var age = students[i].getElementsByTagName("age")[0].childNodes[0].nodeValue;
var course = students[i].getElementsByTagName("course")[0].childNodes[0].nodeValue;
table += "<tr><td>" + id + "</td><td>" + name + "</td><td>" + age + "</td><td>" + course + "</td></tr>";
}
table += "</table>";
document.getElementById("result").innerHTML = table;
}
</script>
</head>
<body>
<h2>Students List (XML via AJAX)</h2>
<button onclick="fetchXML()">Load Students</button>
<div id="result" style="margin-top:20px;"></div>
</body>
</html>
xhr.responseXML automatically parses the XML response into a DOM object.
getElementsByTagName() fetches all <student> elements.
getAttribute() reads the id attribute.
childNodes[0].nodeValue retrieves the text content inside each tag.
The table is dynamically built and displayed in the div.
XML can have nested elements. For example, a student’s contact info:
<student id="1">
<name>Riya Sharma</name>
<age>20</age>
<contact>
<email>riya@example.com</email>
<phone>1234567890</phone>
</contact>
</student>
You can access nested data like this:
var email = students[i].getElementsByTagName("email")[0].childNodes[0].nodeValue;
var phone = students[i].getElementsByTagName("phone")[0].childNodes[0].nodeValue;
getAttribute("id") – Fetches the value of an attribute.
childNodes[0].nodeValue – Fetches the text content inside a tag.
Always check if the element exists to avoid errors:
var emailNode = students[i].getElementsByTagName("email")[0];
var email = emailNode ? emailNode.childNodes[0].nodeValue : "N/A";
Instead of a static XML file, PHP can generate XML dynamically.
PHP File: students.php
<?php
header("Content-Type: text/xml");
$students = [
["id"=>1, "name"=>"Riya Sharma", "age"=>20, "course"=>"Web Development"],
["id"=>2, "name"=>"Ananya Singh", "age"=>22, "course"=>"Data Science"],
["id"=>3, "name"=>"Meera Patel", "age"=>21, "course"=>"UI/UX Design"]
];
echo "<?xml version='1.0' encoding='UTF-8'?>";
echo "<students>";
foreach($students as $s) {
echo "<student id='".$s['id']."'>";
echo "<name>".$s['name']."</name>";
echo "<age>".$s['age']."</age>";
echo "<course>".$s['course']."</course>";
echo "</student>";
}
echo "</students>";
?>
Update the AJAX call to fetch students.php instead of students.xml.
Structured data format – Easy to validate and parse.
Hierarchical representation – Supports nested data.
Cross-language support – Works with PHP, Java, Python, and others.
Dynamic content updates – XML can be generated or modified server-side.
Works with legacy systems – Many older APIs still provide XML data.
Always check if the XML response is valid:
if (!xhr.responseXML) {
alert("Failed to load XML data");
return;
}
Handle missing nodes gracefully to prevent JavaScript errors.
AJAX can work with XML data to create dynamic, responsive web pages. Key points:
Use XMLHttpRequest to fetch XML asynchronously.
Use responseXML to parse XML automatically into a DOM object.
Access elements using getElementsByTagName() and attributes using getAttribute().
PHP can generate XML dynamically for AJAX requests.
Useful for APIs, legacy systems, and structured hierarchical data.
This method is essential for web applications that need to fetch and display XML data dynamically without reloading the page.
Create an HTML page that fetches a static students.xml file via AJAX and displays student names in a table.
Modify the previous example to also display the id and age attributes of each student.
Create a nested XML file with <contact> details (email and phone) and fetch it dynamically using AJAX, displaying all information.
Use PHP to generate XML dynamically for a list of students and fetch it with AJAX.
Write a function that fetches XML and highlights students who are older than 21.
Implement error handling in AJAX to alert if the XML file cannot be loaded.
Create a live dropdown that fetches different XML files (e.g., students from different courses) and updates a table dynamically.
Parse an XML file with missing nodes and display “N/A” where data is unavailable.
Combine AJAX XML with a search input to filter students by name dynamically.
Create a table with “Edit” and “Delete” buttons for each student fetched via AJAX XML (just display the buttons, no database needed yet).