Dynamically loading content with Ajax and PHP

Ajax is a web technique used to dynamically check and load content on the fly without reloading the web browser. It is accomplished using JavaScript and some sort of server side scripting such as PHP. In this tutorial I’ll show you how to generate a random number quickly without reloading the page using JavaScript and PHP. Using this example, it’s easy to expand upon with a foundation in JavaScript and PHP to produce the result you would like in a large variety of web applications.

In a typical setup, we will need three things:

  1. An HTML Page
  2. A JavaScript File
  3. A PHP Page

In the HTML page, we will simply need three things. First, we need to include a JavaScript file to include our Ajax in. Another thing would be an action that would call the script. In this case that will be a link that calls the javascript getRand() function. This function will be defined in the JavaScript file we included. The last thing would be somewhere to put our results. In this case, it’s an empty div tag with the id of displayarea. The HTML file may be called whatever you’d like, but in this case we will use index.html. Here’s the complete code for the HTML code in this example:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
  "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
	<title>Ajax PHP</title>
	<script type="text/javascript" src="ajax.js"></script>
</head>
<body>
	<a href="javascript:getRand()">Show Random Number</a>
	<div id="displayarea"></div>
</body>
</html>

Because the PHP page is so simple in this case, I’ll go ahead and explain it before getting into the Ajax part. In this example, all our PHP page will do is display a random number. This is accomplished using PHP’s rand() function. We will call this file server.php:

<?php
	echo rand();
?>

For the JavaScript file, we will need to include all of the logic for the Ajax request. Basically, we will have to create an XMLHttpRequest object, which will be used to open a link to our dynamic page (PHP) and put the data into our container(the div tag). To add support for old browsers, we can also check to see which kind of object we should create. If we only wanted to support new browsers, we could use this:

xmlHttpRequest = new XMLHttpRequest();

Because we’d also like to support Internet Explorer 5 and 6, we will need to write a function to see which kind of object we will take. You can read more about this here.

// Produce the object for the correct browser
// May be modified to support more older browsers
function getXmlHttpRequest()
{
	// Microsoft Internet Explorer 5 & 6
	if (window.ActiveXObject)
		return new ActiveXObject("Microsoft.XMLHTTP");
	// Modern browsers such as Firefox, IE7, Safari, Chrome, and Opera7.6+
	else if (window.XMLHttpRequest)
		return new XMLHttpRequest();
	else
	{
		alert("Please upgrade your browser to use Ajax");
		return null;
	}
}

Now, we need to do something with this object. We made it so when we click the link, it calls the JavaScript function getRand(). With the JavaScript, we can take the XMLHttpRequest object we generated earlier and invoke the open and send functions to load our desired PHP page. The method information for these can be find here(open) and here(send).

// Page to open
xmlHttpRequest.open("GET", "server.php", true);
xmlHttpRequest.send(null);

By using true as the 3rd parameter in the open method, it will run a callback to an onreadystatechange method. We can define this method and check to see if the state it’s sending is when the page has completed loading(4). By doing that, when the open method has finished loading the page, our desired changes in the website will take effect. The send method will send the HTTP request to the server.

// This function tells us how far along the page is with loading
xmlHttpRequest.onreadystatechange = function()
{
	// When the readystate is 4, the page has been completely loaded
	if(xmlHttpRequest.readyState == 4)
		// What is changed in the document when the page is loaded
		document.getElementById("displayarea").innerHTML = xmlHttpRequest.responseText;
}

In this example, all that happens is the JavaScript finds the displayarea div tag and replaces the html inside of it with the response from our server.php page.

Here’s the complete code for the getRand() JavaScript method:

// When action is called, main logic
function getRand()
{
	// Get the XMLHttpRequest Object from our function above that checks
	// browser compatibility and retrieves the correct object
	xmlHttpRequest = getXmlHttpRequest();
	if (xmlHttpRequest != null)
	{
		// Page to open
		xmlHttpRequest.open("GET", "server.php", true);
		xmlHttpRequest.send(null); 
 
		// This function tells us how far along the page is with loading
		xmlHttpRequest.onreadystatechange = function()
		{
			// When the readystate is 4, the page has been completely loaded
			if(xmlHttpRequest.readyState == 4)
				// What is changed in the document when the page is loaded
				document.getElementById("displayarea").innerHTML = xmlHttpRequest.responseText;
		}
	}
}

This random number generator exmaple of Ajax may be adapted to work with many applications such as a navigation bar or login form. A working example can be found here. The complete source code can be downloaded here.

More Resources:
http://www.ibm.com/developerworks/web/library/wa-ajaxintro1.html
http://www.w3schools.com/php/php_ajax_intro.asp