Ajax Applications in XML
? AJAX Applications in XML
AJAX (Asynchronous JavaScript and XML) allows web pages to communicate with a server in the background, without refreshing the whole page.
Originally, XML was the main format used to exchange data in AJAX — hence the name!
? How AJAX Works (with XML)
A JavaScript event triggers a request.
JavaScript creates an XMLHttpRequest object.
It sends a request to the server.
The server processes the request and sends XML data back.
JavaScript processes the XML and updates the webpage dynamically.
? Example: Using AJAX to Load XML Data
? Sample XML File (data.xml)
<employees> <employee> <name>Vikash Gupta</name> <position>Developer</position> </employee> <employee> <name>Ravi Kumar</name> <position>Designer</position> </employee></employees>? HTML + JavaScript (AJAX)
<!DOCTYPE html><html><head> <title>AJAX with XML</title></head><body><h2>Employee List</h2><div id="output"></div><script> // Create XMLHttpRequest const xhttp = new XMLHttpRequest(); // What to do when response is ready xhttp.onload = function() { const xmlDoc = this.responseXML; const employees = xmlDoc.getElementsByTagName("employee"); let output = "<ul>"; for (let i = 0; i < employees.length; i++) { const name = employees[i].getElementsByTagName("name")[0].childNodes[0].nodeValue; const position = employees[i].getElementsByTagName("position")[0].childNodes[0].nodeValue; output += `<li>${name} - ${position}</li>`; } output += "</ul>"; document.getElementById("output").innerHTML = output; }; // Send request xhttp.open("GET", "data.xml", true); xhttp.send();</script></body></html>? Breakdown
| Step | Description |
|---|---|
xhttp.open("GET", "data.xml", true); | Prepares a request to fetch data.xml. |
xhttp.send(); | Sends the request. |
this.responseXML | Gets the XML response. |
getElementsByTagName() | Extracts specific data from the XML tree. |
? Why Use XML in AJAX?
XML is structured, standardized, and works well with DOM parsers.
Still used in enterprise or legacy systems (e.g., SOAP services).
? Alternatives Today
Modern apps often prefer:
JSON: Smaller, faster to parse, and JavaScript-friendly.
Text/HTML: When rendering snippets of HTML directly.
? Summary
XML is one of the earliest formats used with AJAX.
You can use JavaScript to fetch and parse XML with
XMLHttpRequest.While JSON is more common today, XML is still important for many systems and standards.
Would you like a live demo, a PHP+AJAX+XML example, or how to convert XML to JSON in JS?