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

Ajax the easy way with jQuery

To start off, I’d highly recommend learning about Ajax using XMLHttpRequest objects here. To supplement that tutorial, I’ll talk about doing Ajax in a much easier, much shorter way using the jQuery JavaScript Library. Using jQuery for Ajax is much quicker, easier, and less time-consuming.

Like a normal Ajax setup, we’ll need 3 things:

  1. An HTML Page
  2. A JavaScript File
  3. A server side script (In this case, a PHP page again)

We can use the same HTML and PHP pages as in my last example. Those are explained here. In short, the HTML page just contains a link to generate a random number. The PHP page contains the code to provide a random number. What the JavaScript file will do is use Ajax to dynamically load the PHP page into the empty div tag we provide when the link is clicked without refreshing the page.
The code for the HTML page is exactly the same as a non-jQuery Ajax example, except that we also have to load the jQuery Library in our head tag.

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>

This also requires that jQuery is downloaded and put in the same directory as the HTML file (unless the src attribute is changed). jQuery may be downloaded here. Here’s the full HTML file for 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="jquery-1.3.2.min.js"></script>
	<script type="text/javascript" src="ajax.js"></script>
</head>
<body>
	<a href="javascript:getRand()">Show Random Number</a>
	<div id="displayarea"></div>
</body>
</html>

And the PHP page(server.php):

<?php
	echo rand();
?>

Now, in my previous example, there was a good bit of JavaScript. With jQuery, we only need one line in the method for simple examples like this.

// When action is called, main logic
function getRand()
{
	$("#displayarea").load("server.php");
}

Now I’ll explain what the does. In jQuery, starting a line with a $ symbol basically tells jQuery that you’d like to use the library. The first part, $(”#displayarea”), selects our displayarea div tag. In jQuery that’s how you do the JavaScript method getElementById. The load method does all the Ajax for us by loading the page and inserting what it retrieves into the div tag we just selected.

By default, such as in the example, the load method will just use GET to load the page. If you supply additional parameters, such as this, a POST will be performed:

// When action is called, main logic
function getRand()
{
	myvar = "hello";
	$("#displayarea").load("server.php", attribute: myvar );
}

That attributes may be accessed in the PHP page via $_POST['attribute']. To supply more than one attribute, you can put the whole 2nd parameter in brackets and seperate each attribute by a comma like this:

// When action is called, main logic
function getRand()
{
	myvar1 = "hello";
	myvar2 = "world";
	$("#displayarea").load("server.php", { attribute1: myvar1, attribute2: myvar2 } );
}

Furthermore, if you’d like to specify if you want it to GET or POST, you may just replace load with the method get or post. Since the load method can take 1, 2, or 3 parameters. The 3rd one would be a callback function. This function would be called when the Ajax is complete whether or not it was successful.
Ajax has many more useful applications, and a listing of all the methods may be found here:
http://docs.jquery.com/Main_Page
This Ajax random number generator can easily be applied to other applications such as a navigation or login form. You may find a working example here and the source code to each file here.

More resources:
http://docs.jquery.com/Tutorials
http://www.ibm.com/developerworks/web/library/wa-jquery1/