Ajax anh PHP XML example

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


AJAX XML Example

In the AJAX example below we will demonstrate how a web page can fetch information from an XML file using AJAX technology.


Select a CD in the Box Below

Select a CD: Bob Dylan Bee Gees Cat Stevens

CD info will be listed here.

This example consists of four pages:

  • a simple HTML form
  • an XML file
  • a JavaScript
  • a PHP page

The HTML Form

The example above contains a simple HTML form and a link to a JavaScript:

<html>
<head>
<script src="selectcd.js"></script>
</head>
<body>
<form>
Select a CD:
<select name="cds" onchange="showCD(this.value)">
<option value="Bob Dylan">Bob Dylan</option>
<option value="Bee Gees">Bee Gees</option>
<option value="Cat Stevens">Cat Stevens</option>
</select>
</form>
<p>
<div id="txtHint"><b>CD info will be listed here.</b></div>
</p>
</body>
</html>

Example Explained

As you can see it is just a simple HTML form with a simple drop down box called “cds”.

The paragraph below the form contains a div called “txtHint”. The div is used as a placeholder for info retrieved from the web server.

When the user selects data, a function called “showCD” is executed. The execution of the function is triggered by the “onchange” event.

In other words: Each time the user changes the value in the drop down box, the function showCD is called.


The XML File

The XML file is “cd_catalog.xml“. This document contains a CD collection.


The JavaScript

This is the JavaScript code stored in the file “selectcd.js”:

var xmlHttp

function showCD(str)
{
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
 {
 alert ("Browser does not support HTTP Request")
 return
 }
var url="getcd.php"
url=url+"?q="+str
url=url+"&sid="+Math.random()
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}

function stateChanged()
{
 if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
 {
 document.getElementById("txtHint").innerHTML=xmlHttp.responseText
 }
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
 {
 // Firefox, Opera 8.0+, Safari
 xmlHttp=new XMLHttpRequest();
 }
catch (e)
 {
 // Internet Explorer
 try
  {
  xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
  }
 catch (e)
  {
  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
 }
return xmlHttp;
}

Example Explained

The stateChanged() and GetXmlHttpObject functions are the same as in the last chapter, you can go to the previous page for an explanation of those

The showCD() Function

If an item in the drop down box is selected the function executes the following:

  1. Calls on the GetXmlHttpObject function to create an XMLHTTP object
  2. Defines the url (filename) to send to the server
  3. Adds a parameter (q) to the url with the content of the input field
  4. Adds a random number to prevent the server from using a cached file
  5. Call stateChanged when a change is triggered
  6. Opens the XMLHTTP object with the given url.
  7. Sends an HTTP request to the server

The PHP Page

The server paged called by the JavaScript, is a simple PHP file called “getcd.php”.

The page is written in PHP using the XML DOM to load the XML document “cd_catalog.xml“.

The code runs a query against the XML file and returns the result as HTML:

<?php
$q=$_GET["q"];
$xmlDoc = new DOMDocument();
$xmlDoc->load("cd_catalog.xml");
$x=$xmlDoc->getElementsByTagName('ARTIST');
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)
    {
    $y=($x->item($i)->parentNode);
    }
  }
}
$cd=($y->childNodes);
for ($i=0;$i<$cd->length;$i++)
{
//Process only element nodes
if ($cd->item($i)->nodeType==1)
  {
  echo($cd->item($i)->nodeName);
  echo(": ");
  echo($cd->item($i)->childNodes->item(0)->nodeValue);
  echo("<br />");
  }
}
?>

Example Explained

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

  1. PHP creates an XML DOM object of the “cd_catalog.xml” file
  2. All “artist” elements (nodetypes = 1) are looped through to find a name matching the one sent from the JavaScript.
  3. The CD containing the correct artist is found
  4. The album information is output and sent to the “txtHint” placeholder
Advertisements

AJAX

AJAX = Asynchronous JavaScript And XML

AJAX is an acronym for Asynchronous JavaScript And XML.

AJAX is not a new programming language, but simply a new technique for creating better, faster, and more interactive web applications.

AJAX uses JavaScript to send and receive data between a web browser and a web server.

The AJAX technique makes web pages more responsive by exchanging data with the web server behind the scenes, instead of reloading an entire web page each time a user makes a change.


AJAX Is Based On Open Standards

AJAX is based on the following open standards:

  • JavaScript
  • XML
  • HTML
  • CSS

The open standards used in AJAX are well defined, and supported by all major browsers. AJAX applications are browser and platform independent. (Cross-Platform, Cross-Browser technology)


AJAX Is About Better Internet Applications

Web applications have many benefits over desktop applications:

  • they can reach a larger audience
  • they are easier to install and support
  • they are easier to develop

However, Internet applications are not always as “rich” and user-friendly as traditional desktop applications.

With AJAX, Internet applications can be made richer (smaller, faster, and easier to use).


You Can Start Using AJAX Today

There is nothing new to learn.

AJAX is based on open standards. These standards have been used by most developers for several years.

Most existing web applications can be rewritten to use AJAX technology instead of traditional HTML forms.


AJAX Uses XML And HTTP Requests

A traditional web application will submit input (using an HTML form) to a web server. After the web server has processed the data, it will return a completely new web page to the user.

Because the server returns a new web page each time the user submits input, traditional web applications often run slowly and tend to be less user friendly.

With AJAX, web applications can send and retrieve data without reloading the whole web page. This is done by sending HTTP requests to the server (behind the scenes), and by modifying only parts of the web page using JavaScript when the server returns data.

XML is commonly used as the format for receiving server data, although any format, including plain text, can be used.

You will learn more about how this is done in the next chapters of this tutorial.


PHP and AJAX

There is no such thing as an AJAX server.

AJAX is a technology that runs in your browser. It uses asynchronous data transfer (HTTP requests) between the browser and the web server, allowing web pages to request small bits of information from the server instead of whole pages.

AJAX is a web browser technology independent of web server software.

However, in this tutorial we will focus more on actual examples running on a PHP server, and less on how AJAX works.