AJAX can be used for interactive communication with an XML file.
AJAX XML Example
The following example will demonstrate how a web page can fetch information from an XML file with AJAX:
Example
When the button was clicked:
| Artist |
---|---|
Empire Burlesque | Bob Dylan |
Hide your heart | Bonnie Tyler |
Greatest Hits | Dolly Parton |
Still got the blues | Gary Moore |
Eros | Eros Ramazzotti |
One night only | Bee Gees |
Sylvias Mother | Dr.Hook |
Maggie May | Rod Stewart |
Romanza | Andrea Bocelli |
When a man loves a woman | Percy Sledge |
Black angel | Savage Rose |
1999 Grammy Nominees | Many |
For the good times | Kenny Rogers |
Big Willie style | Will Smith |
Tupelo Honey | Van Morrison |
Soulsville | Jorn Hoel |
The very best of | Cat Stevens |
Stop | Sam Brown |
Bridge of Spies | T'Pau |
Private Dancer | Tina Turner |
Midt om natten | Kim Larsen |
Pavarotti Gala Concert | Luciano Pavarotti |
The dock of the bay | Otis Redding |
Picture book | Simply Red |
Red | The Communards |
Unchain my heart | Joe Cocker |
Example Explained
When a user clicks on the "Get CD info" button above, the loadDoc() function is executed.
The loadDoc() function creates an XMLHttpRequest object, adds the function to be executed when the server response is ready, and sends the request off to the server.
When the server response is ready, an HTML table is built, nodes (elements) are extracted from the XML file, and it finally updates the element "demo" with the HTML table filled with XML data:
LoadXMLDoc()
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
myFunction(xhttp);
}
};
xhttp.open("GET", "cd_catalog.xml", true);
xhttp.send();
}
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>Artist</th><th>Title</th></tr>";
var x = xmlDoc.getElementsByTagName("CD");
for (i = 0; i <x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue +
"</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}
The XML File
The XML file used in the example above looks like this: "cd_catalog.xml".