Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PHP AJAX with XML Example

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:















Select a CD:
CD info will be listed here...

The showCD() function performs the following steps:


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:

  1. PHP creates an XML DOM object
  2. Find all elements whose names match the data sent by JavaScript
  3. Output the album information and send it back to the "txtHint" placeholder