Ajax Xmlhttp in XML
AJAX XMLHttpRequest with XML — Explained
AJAX uses the XMLHttpRequest object to send requests to the server and receive responses asynchronously. When the response is XML, you can parse it easily using the responseXML property.
How XMLHttpRequest Works with XML
Create a new
XMLHttpRequestobject.Open a connection to the server (
GETorPOST).Send the request.
Wait for the server’s response.
Parse the response as XML using
responseXML.Extract data from the XML and update the webpage.
Simple Example: Load XML Data with XMLHttpRequest
Sample XML file: info.xml
<?xml version="1.0" encoding="UTF-8"?><users> <user> <name>Alice</name> <email>alice@example.com</email> </user> <user> <name>Bob</name> <email>bob@example.com</email> </user></users>HTML + JavaScript to fetch and parse XML
<!DOCTYPE html><html><head> <title>AJAX XMLHttpRequest XML Example</title></head><body><h2>User List</h2><button onclick="loadUsers()">Load Users</button><div id="userList"></div><script>function loadUsers() { const xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState === 4 && this.status === 200) { // Parse the XML response const xmlDoc = this.responseXML; // Get all <user> elements const users = xmlDoc.getElementsByTagName("user"); let output = "<ul>"; for (let i = 0; i < users.length; i++) { const name = users[i].getElementsByTagName("name")[0].textContent; const email = users[i].getElementsByTagName("email")[0].textContent; output += `<li>${name} — ${email}</li>`; } output += "</ul>"; document.getElementById("userList").innerHTML = output; } }; xhttp.open("GET", "info.xml", true); xhttp.send();}</script></body></html>Summary
| Step | What happens |
|---|---|
new XMLHttpRequest() | Create AJAX request object |
open("GET", "info.xml") | Prepare GET request to XML file |
send() | Send the request |
responseXML | Get parsed XML document from response |
getElementsByTagName() | Extract specific XML elements (user, name) |
| Update HTML | Show extracted data dynamically |
If you want, I can help with:
Using POST with XML data.
Parsing complex XML structures.
Converting XML to JSON with JavaScript.
Just ask!