How to Use AJAX With XML

Introduction

Asynchronous JavaScript and XML (AJAX) can be used for interactive communication with an XML file. Extensible Markup Language (XML) is a special format for structuring and storing data in files, conventionally with the "xml" extension (such as filename.xml). In some cases, the response received by AJAX (data transmitted from the server script) can be an XML document. This method is commonly used in API applications when data is transferred from one server to another (from an external server to the site that has requested the transfer).
This Example shows you how to get data from an XML file and display it in the web page, using AJAX.

Example

The example will demonstrate how a web page can fetch information from an XML file with AJAX. This file is saved as axml.php. AJAX allows content on Web pages to be updated immediately when a user performs an action, unlike an HTTP request.

ajax with xml.jpg

HTML Page

<html>//HTML page start here

<head>

<script>

    function showCD(str)

    {

        if (str == "")

        {

            document.getElementById("txtHint").innerHTML = "";

            return;

        }

        if (window.XMLHttpRequest)

        {

            xmlhttp = new XMLHttpRequest();

        }

        else

        {

            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

        }

        xmlhttp.onreadystatechange = function ()

           {

            if (xmlhttp.readyState == 4 && xmlhttp.status == 200)

            {

                document.getElementById("txtHint").innerHTML = xmlhttp.responseText;

            }

        }

        xmlhttp.open("GET", "getcd.php?q=" + str, true);

        xmlhttp.send();

    }

</script>

 

<style type="text/css">

<!--

.style1 {

       font-size: 16pt;

       color: #990000;

       font-weight: bold;

}

.style2 {

       color: #990033;

       font-weight: bold;

}

.style3 {color: #0909FF}

.style4 {color: #0000FF}

-->

</style>

 

</head>

<body bgcolor="#ADDCDC">

<form class="style1">

<span class="style3">Select a CD</span>:

  <select name="cds" class="style2" onChange="showCD(this.value)">

    <option value="">Select a CD:</option>

    <option value="3 Idiots">3 Idiots</option>

    <option value="Wanted">Wanted</option>

    <option value="Jorn Hoel">Jorn Hoel</option>

    <option value="Van Morrison">Van Morrison</option>

    <option value="Sam Brown">Sam Brown</option>

    <option value="Rajput">Rajput</option>

    <option value="Rockstar">Rockstar</option>

  </select>

</form>

<div class="style2" id="txtHint"><font color="#591B0B"><span class="style4">Movie info will be listed here...</span></div>

</body>

</html>

The "showCD()" function does the following:

  • If a CD is selected.

  • Create an XMLHttpRequest object.

  • Create the function to be executed when the server response is ready.

  • Send the request off to a file on the server.

  • Notice that a parameter (q).

PHP File

Save this file "getcd.php" and include it in axml.php. The page on the server called by the Js (JavaScript) above is a PHP file called "getcd.php". The PHP script loads an XML document, "cd_catalog.xml", runs a query against the XML file, and returns the result as HTML:

<?php

$q=$_GET["q"];

 

$xmlDoc = new DOMDocument();

$xmlDoc->load("cd.xml");

 

$x=$xmlDoc->getElementsByTagName('ARTIST');

 

for ($i=0; $i<=$x->length-1; $i++)

{

//Process only element nodes

if ($x->item($i)->nodeType==1)

  {

  if ($x->item($i)->childNodes->item(0)->nodeValue == $q)

    {

    $y=($x->item($i)->parentNode);

    }

  }

}

 

$cd=($y->childNodes);

 

for ($i=0;$i<$cd->length;$i++)

{

if ($cd->item($i)->nodeType==1)

  {

  echo("<b>" . $cd->item($i)->nodeName . ":</b> ");

  echo($cd->item($i)->childNodes->item(0)->nodeValue);

  echo("<br>");

  }

}

?>

When the CD query is sent from the JavaScript to the PHP page.

  • PHP creates an XML DOM object

  • Find all <artist> elements that match the name sent from the JavaScript such as <artist>Wanted</artist>

  • Output the album information (sent to the "txtHint" placeholder)
     

XML Data File

The first step is getting data from XML. This data may be received from PHP (or other server application) as a string with XML format, or can be downloaded directly from an XML file.
After the XML data were received, it must be loaded (stored) in a JavaScript DOM object.
If the XML content is received in a single string, from a server side script, the JavaScript code to load that XML format in a JS DOM object is the fallowing (explanations are in the script code). This file is saved as cd.xml.

<CATALOG>

<CD>

<TITLE>All is well</TITLE>

<ARTIST>3 Idiots</ARTIST>

<COUNTRY>India</COUNTRY>

<COMPANY>Bolybood Film</COMPANY>

<PRICE>Asker award</PRICE>

<YEAR>2009</YEAR>

</CD>

<CD>

<TITLE>Mera hi jalawa</TITLE>

<ARTIST>Wanted</ARTIST>

<COUNTRY>India</COUNTRY>

<COMPANY>Bolybood Film</COMPANY>

<PRICE>Superhit</PRICE>

<YEAR>Sep 2009</YEAR>

</CD>

<CD>

<TITLE>Greatest Hits</TITLE>

<ARTIST>Rockstar</ARTIST>

<COUNTRY>India</COUNTRY>

<COMPANY>Bolybood</COMPANY>

<PRICE>Asker award</PRICE>

<YEAR>Dec 2011</YEAR>

</CD>

<CD>

<TITLE>One night only</TITLE>

<ARTIST>Bee Gees</ARTIST>

<COUNTRY>UK</COUNTRY>

<COMPANY>Polydor</COMPANY>

<PRICE>10.90</PRICE>

<YEAR>1998</YEAR>

</CD>

<CD>

<TITLE>Sylvias Mother</TITLE>

<ARTIST>Dr.Hook</ARTIST>

<COUNTRY>UK</COUNTRY>

<COMPANY>CBS</COMPANY>

<PRICE>8.10</PRICE>

<YEAR>1973</YEAR>

</CD>

<CD>

<TITLE>Maggie May</TITLE>

<ARTIST>Rod Stewart</ARTIST>

<COUNTRY>UK</COUNTRY>

<COMPANY>Pickwick</COMPANY>

<PRICE>8.50</PRICE>

<YEAR>1990</YEAR>

</CD>

<CD>

<TITLE>Romanza</TITLE>

<ARTIST>Andrea Bocelli</ARTIST>

<COUNTRY>EU</COUNTRY>

<COMPANY>Polydor</COMPANY>

<PRICE>10.80</PRICE>

<YEAR>1996</YEAR>

</CD>

<CD>

<TITLE>When a man loves a woman</TITLE>

<ARTIST>Percy Sledge</ARTIST>

<COUNTRY>USA</COUNTRY>

<COMPANY>Atlantic</COMPANY>

<PRICE>8.70</PRICE>

<YEAR>1987</YEAR>

</CD>

<CD>

<TITLE>1999 Grammy Nominees</TITLE>

<ARTIST>Rajput</ARTIST>

<COUNTRY>india</COUNTRY>

<COMPANY>Grammy</COMPANY>

<PRICE>Superhit</PRICE>

<YEAR>1982</YEAR>

</CD>

<CD>

<TITLE>Big Willie style</TITLE>

<ARTIST>Will Smith</ARTIST>

<COUNTRY>USA</COUNTRY>

<COMPANY>Columbia</COMPANY>

<PRICE>9.90</PRICE>

<YEAR>1997</YEAR>

</CD>

<CD>

<TITLE>Soulsville</TITLE>

<ARTIST>Jorn Hoel</ARTIST>

<COUNTRY>Norway</COUNTRY>

<COMPANY>WEA</COMPANY>

<PRICE>7.90</PRICE>

<YEAR>1996</YEAR>

</CD>

<CD>

<TITLE>The very best of</TITLE>

<ARTIST>Cat Stevens</ARTIST>

<COUNTRY>UK</COUNTRY>

<COMPANY>Island</COMPANY>

<PRICE>8.90</PRICE>

<YEAR>1990</YEAR>

</CD>

<CD>

<TITLE>Stop</TITLE>

<ARTIST>Sam Brown</ARTIST>

<COUNTRY>UK</COUNTRY>

<COMPANY>A and M</COMPANY>

<PRICE>8.90</PRICE>

<YEAR>1988</YEAR>

</CD>

<CD>

</CATALOG>

Output

ajax with xml1.jpg

ajax with xml4.jpg

ajax with xml3.jpg

ajax with xml2.jpg


Similar Articles