AJAX for beginners

The advent of AJAX (Asynchronous Javascript and XML) has opened up new doors to web developers, allowing for interaction with and display of database and other external data in a web document, without the need to load a new page.

This is my tutorial for beginners wanting to use AJAX on their websites.


AJAX is made possible by a DOM API by the name of xmlHttpRequest, which allows HTTP or HTTPS requests to be initiated and handled from within Javascript.

Below is the function to place in your .js file for the current document.

function xmlRequest(){
	var xmlHttp=null;
	if (window.XMLHttpRequest) {
  	// code for IE7+, Firefox, Chrome, Opera, Safari
  		xmlHttp=new XMLHttpRequest();
	else if (window.ActiveXObject) {
  // code for IE6, IE5
		xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		alert("Your browser does not support XMLHTTP!");
	return xmlHttp;

Grabbing and Displaying a Record-set

Suppose you wanted to display data on your website that is updated every 10 seconds, showing a list of recent entries into a shout-out wall table, looking a bit like this:

Louis: Love the site!

Disregarding the process beyond the scope of this tutorial (of entering the data into the database), we will need to take these steps to achieve this outcome:

1. Write the query and output server-side script (php for this tutorial)

2. Write some javascript to request the server-side script, and output the response to a designated area of the site.

The Shout-out Table

In the database, we will have a table called “shoutouts” with the following structure:

soID(int,auto_increment),userName(varchar 50),shoutOutMsg(varchar 255)

The PHP script

The script below will show you how to query the database and output the results. The query uses a limit to display only the most recent shout-outs.


include "connect.php";
$sql="SELECT * FROM shoutouts ORDER BY soID DESC LIMIT 5";
if (mysql_errno()){
	echo "ERROR|".mysql_error();
} else {
	echo "OK|";
	for ($row=mysql_fetch_assoc($result)){
		echo "<strong>".$row['userName']."</strong>: ".$row['shoutOutMsg']."";

We use “ORDER BY soID DESC” to make the latest posts show up first, and “LIMIT 5″ to select the first 5 out of this reversed order set. The script then loops through each of the 5 records and outputs a row of html that displays the user name and message.


We need a place within our document to put the shouts. You can create elements with javascript, but for beginners it may be easier to simply add a placeholder element in the source document. Either way, the element must have an ID that can be called upon later by the javascript function, looking like this:

The Javascript

Our Javascript will consist of a function that will request the data and subsequently insert it into the document. You should take note that the function called upon by this script “xmlRequest” was shown at the beginning of the tutorial.

function getShoutOuts(){
	var xmlObject=new xmlRequest();
		if (xmlObject.readyState==4){
			var returnString=xmlObject.responseText.split("|");
			if (returnString[0]=="OK"){
				//query was successful
				var returnedHTML=returnString[1];
			} else if (returnString[0]=="ERROR"){
				//query failed in php and reported an error
	var t=setTimeout(getShoutOuts,10000);

Simply invoke the function getShoutOuts() on the loading of your document, and the 5 most recent shoutOut entries will be displayed on your page within the shoutContainer div element.

General note about the Ajax Request:

There’s a lot I could say about dealing with these AJAX requests, but something that is often not noticed when starting to use them, is that the onreadystatechange function you construct, will not execute until data is returned. So even though it is above the script below it, it will not execute before it but after it at some point undetermined because of the delay in communications.

What this means… is if you set a variable using data returned from an AJAX request, don’t expect it to be available until xmlObject.readyState==4 and the code within that has been executed.

Leave a comment

Subscribe without commenting