AJAX XML

## AJAX Basic

AJAX HOME AJAX Intro AJAX Example

## AJAX XMLHttpRequest

XHR Create Object XHR Request XHR Response XHR readyState

## AJAX Advanced

AJAX ASP/PHP AJAX Database AJAX XML File

## AJAX Examples

AJAX Examples

# AJAX XML Example

« Previous
Next Chapter »

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

Try it yourself »

## Example Explained - The stateChange() Function

When a user clicks on the "Get CD info" button above, the loadXMLDoc() function is executed.

The loadXMLDoc() 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 txtCDInfo placeholder with the HTML table filled with XML data:

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();
}

## The AJAX Server Page

The page on the server, used in the example above, is an XML file called "cd_catalog.xml".

« Previous
Next Chapter »

## Your suggestion:

Your E-mail (optional):

Page address:

Description:

Close [X]

## Thank You For Helping Us!

Your message has been sent to W3Schools.

Close [X]
Search w3schools.com:

## WEB HOSTING

Best Web Hosting UK Reseller Hosting Wow! $5 SSD Hosting

## WEB BUILDING

Download XML Editor
FREE Website BUILDER FREE Website Creator

## WEB RESOURCES

Web Statistics Web Validation

## SHARE THIS PAGE