PHP Example - AJAX and XML

AJAX can be used to interactively communicate with XML files.

AJAX XML example

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



CD data will be recorded here...

Example explanation-HTML page

When the user selects a CD in the drop-down list above, a function named "showCD ()" is executed. This function is triggered by the "onchange" event:

function showCD(str)
    if (str=="")
    if (window.XMLHttpRequest)
        //IE7+, Firefox, Chrome, Opera, Safari Browser execution
        xmlhttp=new XMLHttpRequest();
        //IE6, IE5 Browser execution
        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>


showCD () function performs the following steps:

  • Check if a CD is selected
  • Creating an XMLHttpRequest object
  • Create a function to be executed when the server response is ready
  • Send a request to a file on the server
  • Please note the parameter (q) added to the end of the URL (including the content of the drop-down list)

PHP file

The above server page called via JavaScript is a PHP file named "getcd.php".


$xmlDoc = new DOMDocument();


for ($i=0; $i<=$x->length-1; $i++)
    //Processing element nodes
    if ($x->item($i)->nodeType==1)
        if ($x->item($i)->childNodes->item(0)->nodeValue == $q)


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

When a CD query is sent from JavaScript to a PHP page, it will happen:

  1. PHP creates XML DOM objects
  2. Find all <artist> The name of the element that matches the data passed by JavaScript
  3. Output information from album and send it back to "txtHint" placeholder