Ajax Request in XML
? AJAX Request and Response in XML – Explained with Example
An AJAX XML request means sending an asynchronous request to the server and receiving data in XML format. JavaScript can then parse and use this XML without reloading the page.
? Basic Flow of an AJAX Request with XML
JavaScript makes an AJAX request using
XMLHttpRequest.The request goes to the server (PHP/ASP/etc.).
The server sends back XML.
The browser's JavaScript parses the XML response.
The page is updated dynamically.
? Example — Send AJAX Request and Receive XML
1?? data.php – Server-Side Script Returning XML
<?phpheader("Content-Type: text/xml");echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";?><books> <book> <title>XML Basics</title> <author>John Smith</author> </book> <book> <title>AJAX in Action</title> <author>Jane Doe</author> </book></books>2?? index.html – AJAX Request Using XMLHttpRequest
<!DOCTYPE html><html><head> <title>AJAX XML Request Example</title></head><body><h2>Book List (From XML Response)</h2><button onclick="loadBooks()">Load Books</button><div id="output"></div><script>function loadBooks() { const xhttp = new XMLHttpRequest(); // When the request completes xhttp.onload = function () { const xmlDoc = this.responseXML; const books = xmlDoc.getElementsByTagName("book"); let output = "<ul>"; for (let i = 0; i < books.length; i++) { const title = books[i].getElementsByTagName("title")[0].textContent; const author = books[i].getElementsByTagName("author")[0].textContent; output += `<li><strong>${title}</strong> by ${author}</li>`; } output += "</ul>"; document.getElementById("output").innerHTML = output; }; xhttp.open("GET", "data.php", true); xhttp.send();}</script></body></html>? How It Works
| Step | What Happens |
|---|---|
xhttp.open(...) | Prepares the GET request to the server |
xhttp.send() | Sends the request |
xhttp.onload | Runs when response is received |
this.responseXML | Accesses returned XML |
getElementsByTagName() | Parses specific tags in XML |
? Notes
The server must return valid XML (with correct headers and format).
You can also send XML data using
xhttp.send(xmlString)with POST.You can use AJAX with any server language — PHP, ASP, Node.js, etc.
? Want to Try More?
Would you like examples of:
Sending XML to server using POST?
Using AJAX + XML + Database?
Comparing XML vs JSON in AJAX?
Let me know and I’ll guide you through!