
This article is well over a year old, and while the techniques are still valid, I have rewritten large portions of the Javascript code and will not be updating this article. Instead, I encourage you to look at

that is a much more robust implementation of the Javascript than is presented here. It utilizes AJAX connection pooling so you can have multiple requests active at once, plus a more powerful way of sending Javascript back as part of the AJAX request for execution on the client.
Introduction To Ajax
Written by Tim Gallagher - 2005
In my attempts to find a cross-browser, simple (yet extensible) approach to AJAX with PHP on the server I had to find several tutorials. Not all of these were helpful, and some code examples were not simple enough to be of much use. I decided to put down my findings into an article so that the time I spent might be of use to others.
I may be ignoring some great tutorials that are out there, and if so, please send me a note with a link.
Getting to a semi-usable point with my system took me about a week of part-time digging, and coding.
This was done on evenings, and only when I could get an hour here and there to work on it.
My goal was three-fold.
- The ability to have PHP output discrete portions of a page (a major part of AJAX)
- To be able to take those different pieces and have a simple way to update the html page
- To be able to submit form information to a script and have the results returned as in point 1.
PHP:
During my research I found three different data formats for sending data back to the browser. I’m sure there are other ways, but these are the ones that seemed prevalent.
- Special serialized data approach ( Introducing JSON )
- Pros: Less overall data (kilobytes) to send making the transfer of data faster, Multiple programming platforms available for implementation of user interface.
- Cons: Few, need to use php code to create and parse the Javascript Object Notation. There is much PHP code available for this.
This will be the subject of a future tutorial.
- Javascript - Have the server side generate javascript that is then eval’d on the client.
- Pros: Fine Grained control over the actual code that is executing on a client. Also moves browser detection to the server where it can be abstracted in the same language as the rest of the web site.
- Cons: Not portable. To use data requires a javascript engine, not necessarily light-weight in terms of kilobytes. Requires knowledge of multiple programming languages (server side + javascript - this may not be a big deal to some), Data format is not compact.
- XML
- Pros: Standards based. Plethora of libraries available for parsing. Multiple programming platforms available for implementation of user interface. Parsing routines already in place in Javascript for easy parsing of response data. Data can be read by other systems.
- Cons: Verbose, requires basic knowledge of xml patterns. Data format is not as compact as JSON, and probably not as compact as eval’d javascript.
For my foray into ajax I chose the XML path. The idea of using XML in other places or applications played a large part in this decision. Also, the PHP I would need to write was much simpler. This point of this article is not to debate the merits of one approach over another, but to introduce ajax in a way that is simple, yet powerful enough to be useful.
The PHP Script
One of the first things I realized was that I didn’t want to have multiple http requests to the server for each page update. One of the first methods I tried was to use a javascript function call to load a single portion of the page at a time. I would group these function calls into functions of their own and simply call that function when I wanted to load a particular page type. I quickly realized the ignorance of this approach for the overhead of multiple connections to the server when I already knew what bits of information I needed.
Since I use PHP on the server and since I love arrays - especially associative arrays - I chose to write a PHP function to take an associative array and output formatted XML based on the key and value of each entry in the array.
Then I got to thinking some more. I really wanted to update large portions of each page with a chunk of HTML (or XHTML). I realized that each part of a page I wanted to fill with content could be referenced via its ID property.
Therefore, the associative array keys are the IDs and the values are the innerHTML for those IDs.
This PHP function generates the XML file that contains all the update items to set the innerHTML for each given ID.
function generateXMLPage( $pieces )
{
$out = "<xml version="\"1.0\"" encoding="\"UTF-8\"" standalone="\"yes\"">" . NL;
$out .= "<response>" . NL;
foreach ($pieces as $divName => $value)
{
$out .= " <item>" . NL;
$out .= " <data><!--[CDATA[" . $value . "]]--></data>" . NL;
$out .= " <divid>" . $divName . "</divid>" . NL;
$out .= " </item>" . NL;
}
$out .= "</response>" . NL;
$out .= "</xml>" . NL;
return $out;
}
$pieces['mainBody'] = "This is the main body of the page's content.";
$pieces['navBar'] = "Login<br />Sign Up";
header('Content-Type: text/xml');
echo generateXMLPage( $pieces );
The Javascript Code
This section of code sets up a cross-browser compatible global variable for performing the xmlHttpRequest. This code is not original to me, it’s code I’ve seen in most of the tutorials online.
<script type="text/javascript">
var xmlhttp=false;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
try
{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (E)
{
xmlhttp = false;
}
}
@end @*/
if (!xmlhttp & typeof XMLHttpRequest != 'undefined')
{
xmlhttp = new XMLHttpRequest();
}
getData takes a node from XML parsing and returns the value for myNodeName. We use this in processXmlResponse to obtain the divid and data portions of of each node.
function getData( myNode, myNodeName )
{
var subNodes = myNode.childNodes;
for ( j=0; j < subNodes.length; j++ )
{
var subNode = subNodes.item(j);
if ( subNode.nodeName == myNodeName )
{
// this is cross browser ( ie and firefox ) compatible
return subNode.childNodes.item(0).nodeValue;
}
}
return "";
}
processXmlResponse takes a response from updatePage or sendForm and loops through the response nodes that are items (see the PHP script) and sets the div’s innerHTML to the item’s data value
function processXmlResponse( response )
{
nodes = response.getElementsByTagName('item'); // returns only nodes that are item nodes.
// this removes the response and xml nodes
for ( i=0; i < nodes.length; i++ )
{
var node = nodes.item(i);
document.getElementById( getData( node, 'divid' ) ).innerHTML = getData( node, 'data' );
}
}
updatePage sends an HTTP GET command to serverPage and processes the return XML by sending it to processXmlResponse.
function updatePage( serverPage )
{
xmlhttp.open("GET", serverPage);
xmlhttp.onreadystatechange =
function()
{
if (xmlhttp.readyState == 4 & xmlhttp.status == 200)
{
processXmlResponse( xmlhttp.responseXML );
}
}
xmlhttp.send(null);
}
sendForm takes the ID of a form, and the formProcessor and POSTs the fields to the formProcessor. It then takes the return XML and sends it to processXmlResponse.
function sendForm ( formID, formProcessor )
{
var form = document.getElementById( formID );
var elements = form.elements;
query = "";
for ( i = 0; i < elements.length-1; i++ )
{
query = query + elements.item(i).name + "=" + elements.item(i).value + "&";
}
query = query + elements.item(i).name + "=" + elements.item(i).value;
xmlhttp.open("POST", formProcessor );
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.onreadystatechange =
function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
processXmlResponse( xmlhttp.responseXML );
}
}
xmlhttp.send(query);
}
//--> </script>
To use this on a page you could format an anchor tag like:
<a href=”javascript://” onclick=”updatePage(’http://example.com/get_page.php?type=news&id=113′);”>Read Article</a>
Or a button on a form like this:
<input type=”button”name=”Submit” value=”Login” onclick=” sendForm ( ‘LoginFormID’, ‘http://example.com/login_get_results.php’)”>
For web site hosting I recommend - www.bluehost.com

I cannot give a high enough rating for Tim. He is INCREDIBLE. He did not just do everything I asked but he fantastically over-delivered...