PHP Example - AJAX and XML

« Previous Chapter Next Chapter »

AJAX can be used for interactive communication with an XML file.

AJAX XML Example

The Below example will demonstrate how a web page can fetch information from an XML file with AJAX:


CD info will be listed here...

Example Explained - The HTML Page

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

<script type="text/javascript">
function showCD(str)
if (str=="")
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  if (xmlhttp.readyState==4 && xmlhttp.status==200)

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>
<div id="txtHint"><b>CD info will be listed here...</b></div>


The showCD() function does the following:

  • Check 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
  • Note: a parameter (q) is added to the URL (with Content of the dropdown list)

The PHP File

The page on the server called by the JavaScript above is a PHP file called "getcd.html".

The PHP script loads an XML document, "demofile.xml", runs a query against the XML file, and returns the result as HTML:


$xmlDoc = new DOMDocument();


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)


for ($i=0;$i<$cd->length;$i++)
//Process only element nodes
if ($cd->item($i)->nodeType==1)
  echo("<b>" . $cd->item($i)->nodeName . ":</b> ");
  echo("<br />");

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

  1. PHP creates an XML DOM object
  2. Find all <artist> elements that matches the name sent from the JavaScript
  3. Output the album information (send to the "txtHint" placeholder)

« Previous Chapter Next Chapter »

Have Any Suggestion? We Are Waiting To Hear from YOU!

Your Query was successfully sent!