Easy Tutorial
❮ Func Zip Read Func Cal Frenchtojd ❯

PHP Example - AJAX with XML


AJAX can be used to interact with XML files.


AJAX XML Example

The following example demonstrates how a web page can retrieve information from an XML file using AJAX:

Example


Example Explanation - HTML Page

When a user selects a CD from the dropdown list above, a function called "showCD()" is executed. This function is triggered by the "onchange" event:

<html>
<head>
<script>
function showCD(str)
{
    if (str=="")
    {
        document.getElementById("txtHint").innerHTML="";
        return;
    } 
    if (window.XMLHttpRequest)
    {
        // IE7+, Firefox, Chrome, Opera, Safari browsers execute
        xmlhttp=new XMLHttpRequest();
    }
    else
    {
        // IE6, IE5 browsers execute
        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>
</head>
<body>

<form>
Select a CD:
<select name="cds" onchange="showCD(this.value)">
<option value="">Select a CD:</option>
<option value="Bob Dylan">Bob Dylan</option>
<option value="Bonnie Tyler">Bonnie Tyler</option>
<option value="Dolly Parton">Dolly Parton</option>
</select>
</form>
<div id="txtHint"><b>CD info will be listed here...</b></div>

</body>
</html>

The showCD() function performs the following steps:


PHP File

The server-side page called by the JavaScript above is a PHP file named "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_catalog.xml");

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

for ($i=0; $i<=$x->length-1; $i++)
{
    // Process 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++)
{ 
    // Process element nodes
    if ($cd->item($i)->nodeType==1)
    {
        echo("<b>" . $cd->item($i)->nodeName . ":</b> ");
echo($cd->item($i)->childNodes->item(0)->nodeValue);
echo("<br>");
}
}
?>

When a CD query is sent from JavaScript to the PHP page, the following occurs:

❮ Func Zip Read Func Cal Frenchtojd ❯