PHP Example - AJAX with XML
AJAX can be used to communicate interactively with an XML file.
AJAX XML Example
The example below demonstrates how a web page reads information from an XML file through AJAX:
Example
CD info will be listed here...
Example Explanation - HTML Page
When the user selects a CD in the dropdown list above, a function named "showCD()" is executed. This function is triggered by the "onchange" event:
CD info will be listed here...
The showCD() function performs the following steps:
- Check whether a CD is selected
- Create an XMLHttpRequest object
- Create the function to be executed when the server response is ready
- Send a request to the file on the server
- Note the parameter (q) appended to the end of the URL (containing the dropdown list contents)
PHP File
The server page called via JavaScript above is a PHP file named "getcd.php".
The PHP script loads the XML document, "cd_catalog.xml", runs a query against the XML file, and returns the result as HTML:
load("cd_catalog.xml");
$x=$xmlDoc->getElementsByTagName('ARTIST');
for ($i=0; $i<=$x->length-1; $i++)
{
// Process element node
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 node
if ($cd->item($i)->nodeType==1)
{
echo("" . $cd->item($i)->nodeName . ": ");
echo($cd->item($i)->childNodes->item(0)->nodeValue);
echo("
");
}
}
?>
When the CD query is sent from JavaScript to the PHP page, the following happens:
- PHP creates an XML DOM object
- Find all
elements whose names match the data sent by JavaScript - Output the album information and send it back to the "txtHint" placeholder