Latest web development tutorials

AJAX XML

AJAX can be used to communicate interactively with the XML file.


AJAX XML instance

The following example demonstrates how to use AJAX web page to read the information from the XML file:

Examples


try it"


Analysis examples - loadXMLDoc () function

When users click on the "Getting CD information" button will execute loadXMLDoc () function.

loadXMLDoc () function to create XMLHttpRequest object, add the function to be executed when the server response is ready, and sends the request to the server.

When the server response is ready, it will build an HTML table, extracted node (element) from the XML file, and then use the HTML form has been filled in the XML data to update txtCDInfo placeholders:

function loadXMLDoc(url)
{
var xmlhttp;
var txt,xx,x,i;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
txt="<table border='1'><tr><th>Title</th><th>Artist</th></tr>";
x=xmlhttp.responseXML.documentElement.getElementsByTagName("CD");
for (i=0;i<x.length;i++)
{
txt=txt + "<tr>";
xx=x[i].getElementsByTagName("TITLE");
{
try
{
txt=txt + "<td>" + xx[0].firstChild.nodeValue + "</td>";
}
catch (er)
{
txt=txt + "<td>&nbsp;</td>";
}
}
xx=x[i].getElementsByTagName("ARTIST");
{
try
{
txt=txt + "<td>" + xx[0].firstChild.nodeValue + "</td>";
}
catch (er)
{
txt=txt + "<td>&nbsp;</td>";
}
}
txt=txt + "</tr>";
}
txt=txt + "</table>";
document.getElementById('txtCDInfo').innerHTML=txt;
}
}
xmlhttp.open("GET",url,true);
xmlhttp.send();
}


AJAX server page

The above example uses the page server is actually a "named cd_catalog.xml " the XML file.