PHP Example - AJAX and XML

AJAX can be utilized for intuitive correspondence with a XML file.

AJAX XML Example

The following model will show how a website page can bring data from a XML record with AJAX:


CD data will be recorded here...

Example Explained - The HTML Page

When a client chooses a CD in the dropdown list over, a capacity called "showCD()" is executed. The work is activated by the "onchange" event:

work showCD(str) {
  on the off chance that (str=="") {
  on the off chance that (window.XMLHttpRequest) {
   /code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else { /code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  xmlhttp.onreadystatechange=function() {
    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="Bee Gees">Bee Gees</option>
<option value="Cat Stevens">Cat Stevens</option>
<div id="txtHint"><b>CD data will be recorded here...</b></div>


The showCD() work does the following:

  • Check if a CD is selected
  • Create a XMLHttpRequest object
  • Create the capacity to be executed when the server reaction is ready
  • Send the demand off to a record on the server
  • Notice that a parameter (q) is added to the URL (with the substance of the dropdown list)

The PHP File

The page on the server called by the JavaScript above is a PHP document called "getcd.php".

The PHP content loads a XML record, "cd_catalog.xml", runs a question against the XML document, and returns the outcome as HTML:


$xmlDoc = new DOMDocument();


for ($i=0; $i<=$x->length-1; $i++) {
  /Process just component nodes
  on the off chance that ($x->item($i)- >nodeType==1) {
    if ($x->item($i)- >childNodes->item(0)- >nodeValue == $q) {
      $y=($x->item($i)- >parentNode);


for ($i=0;$i<$cd->length;$i++) {
  /Process just component nodes
  on the off chance that ($cd->item($i)- >nodeType==1) {
    echo("<b>" . $cd->item($i)- >nodeName . ":</b> ");
    echo($cd->item($i)- >childNodes->item(0)- >nodeValue);

When the CD question is sent from the JavaScript to the PHP page, the accompanying happens:

  1. PHP makes a XML DOM object
  2. Find all <artist> components that coordinates the name sent from the JavaScript
  3. Output the collection data (send to the "txtHint" placeholder)