AJAX is one of the popular acronym buzzwords in the world of web development technologies. It stands for Asynchronous JavaScript and XML. What it does is allow you to make your website far more dynamic by updating portions in realtime without page reloads (refreshes). This beginners AJAX tutorial will teach you how to write JavaScript code to do some simple screen updates. It’ll focus on a low-level AJAX implementation meaning JavaScript toolkits like jQuery and script.aculo.us will not be used (future tutorials will make use of these high-level time-saving tools). In my opinion, learning AJAX in this manner is far better because you’ll grasp the concept and it will help you move in the direction of using toolkits to simplify your coding (you must crawl before you can walk…). Also, this AJAX tutorial will be the first post in a series I plan on publishing regarding this subject.
Phase 1: Writing the AJAX JavaScript Code – Making the Call
I first learned AJAX from the W3Schools website and will be using their code base as the foundation for this AJAX tutorial. The first step in working with AJAX is to create an object of XMLHttpRequest. The Firefox, Opera, Safari, and Internet Explorer browsers all handle this differently, however code wise the first three are the same. Internet Explorer (yes, Microsoft) has to take a unique approach (putting it nicely) which is different than the other mainstream web browsers. Getting back on point now, the code below is a modified version of what you can find from the W3Schools AJAX Guide for creating a object for XMLHttpRequest (the interface to make AJAX music).
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;
}
The code starts with creating a variable handle for the XMLHttpRequest object and making it null. Within a try and catch block the XMLHttpRequest() method is called. If an object is created then exit the function and return the object. If the object can’t be created then the ActiveX (Microsoft) route is taken by using Msxml2.XMLHTTP and Microsoft.XMLHTTP. If this part fails as well, AJAX isn’t possible with the browser for whatever reason, otherwise after having called this GetXmlHttpObject() function we’ll have an AJAX object to work with. Next we’ll build an AJAX request.
// create xml http object
var objXmlHttp = GetXmlHttpObject();
// open a connection and send the ajax request
objXmlHttp.open("GET", "http://www.domain.com/ajaxresponder.php", true);
objXmlHttp.send();
The AJAX request is composed of a call to the open and send methods of the XmlHttpRequest object. The open method takes three parameters (type of request [GET or POST], URL of the file on the server, and boolean true [asynchronous] or false [synchronous]).
-
Type of Request: GET or POST? Well, it depends on your requirements but most of the time you will be using GET for your AJAX calls. AJAX is information dependent meaning that what you give it will determine what it gives back to you. For example, say you’re providing a weather service and want to get the temperature for a specific zip code. That zip code would be passed as part of the URL in the query string. The file on the server would accept that input and give the temperature as output.
-
URL of file on the server: This URL is where the processing of your data happens. The type of file will be a dynamic server-side scripting language such as PHP that can take your input (via GET or POST), process it, and send back formatted output that you will present to the user’s browser. Using the weather example from above, this script would take the zip code and possibly do a database lookup to get the temperature and pass it back to the AJAX caller.
-
Asynchronous or Synchronous: Once again, depending on your requirements you may choose one option over the other. A high percentage of the time your calls will be asynchronous, which means that once the AJAX call is issued your browser won’t be held up waiting on the response; it can continue doing other tasks and once the response does come in it can be processed. One instance when a synchronous call would be necessary is when the response of a first AJAX call is required by a second call. If you keep it asynchronous then once the first AJAX call is done the second would run right away. There is no guarantee that the first call would be fast enough to get the result to pass to the second call, hence keeping it synchronous forces the order of operations to follow through. Be careful though! If the synchronous call takes a long time processing it can appear that your browser window has locked up!
Phase 2: Crafting a Server-Side PHP Script to Process AJAX Requests
With the JavaScript code in place for invoking the AJAX call the server-side script to handle that call needs to be written. The sole purpose of this script will be to listen for the AJAX call, process the request, and send back output. Because this is AJAX tutorial is being written in a manner with beginners in mind, the server-side script is going to be extremely basic. What it will do is send back a random quote from a famous author. In the next tutorial I’ll take it up a notch by showing you how to integrate a database and fetching data.
I’ll be using PHP to write this server-side script because that is my preferred language, however you can use Perl CGI, Cold Fusion, Microsoft’s Active Server Pages, ASP.NET or another language as long as the server that will be hosting the script can support it. If you don’t know PHP then try and follow along and I’ll explain the code as I go.
<?php
/************************************************
AJAX FAMOUS AUTHOR QUOTE SCRIPT
Quotes Source: www.famousquotesandauthors.com
*************************************************/
// we use an array for the famous author quotes
$quotes_arr = array(
"I know only that what is moral is what you feel good after and what is immoral is what you feel bad after. - Ernest Hemingway",
"Eve left Adam, to meet the Devil in private. - Alexander Pope",
"Democracy is based on the conviction that man has the moral and intellectual capacity, as well as the inalienable right, to govern himself with reason and justice. - Harry S. Truman",
"Crime is a logical extension of the sort of behaviour that is often considered perfectly respectable in legitimate business. - Robert Rice",
"By time and toil we sever What strength and rage could never. - Jean de la Fontaine",
"Human history is in essence a history of ideas. - H. G. Wells"
);
// the quotes are chosen randomly
$quote_choice = rand(0, sizeof($quotes_arr) - 1);
// echo the random quote
echo $quotes_arr[$quote_choice];
?>
This is a very simple PHP script. All it does is define a six string array with the variable name of $quotes_arr. One of those six quotes is chosen at random using the PHP rand() function. What rand() will do is pick a random number between 0 and the size of the array less one (6 – 1 = 5) to serve as an index for choosing a string from the array. Note: PHP arrays are zero-based indexing meaning the first element begins at zero, not one. Finally, using PHP’s echo the chosen quote string is printed out to the browser.
Phase 3: Putting All This AJAX & PHP Coding Stuff Together
The pieces to this AJAX puzzle are on the table, it’s time to fit them together. We’ve learned how to build an AJAX request and what an AJAX processing script can look like, the last step is to build the HTML page that makes use of them. The mechanics will be once the page loads the AJAX request will be made, the famous quote will be received from the server-side script, and the quote will be written to the HTML page. I’ve also included a button that can be clicked to load a new quote when clicked.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>AJAX Tutorial: Random Famous Quotes</title>
</head>
<body>
<script type="text/javascript" language="JavaScript">
<!--
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;
}
// create xml http object
var objXmlHttp = GetXmlHttpObject();
// open a connection and send the ajax request
objXmlHttp.open("GET", "http://www.tonybhimani.com/files/2011/10/ajax-quotes.php", true);
objXmlHttp.send();
objXmlHttp.onreadystatechange=function() {
if (objXmlHttp.readyState == 4 && objXmlHttp.status == 200) {
document.getElementById("quotes").innerHTML = objXmlHttp.responseText;
}
}
// -->
</script>
<p><strong>Random Quote of the Day</strong></p>
<p id="quotes"> </p><br />
<p><input type="button" name="reload" value="Reload Page" onclick="javascript:window.location.reload(true);" /></p>
</body>
</html>
You may notice I’ve added some extra code to the AJAX JavaScript section. Because this is an asynchronous call we have to declare an event handler. An event handler is a code block that sits around and waits for an event to occur before it executes its code. Our event handler (JavaScript function) is attached to the onreadystatechange event of the XMLHttpRequest object. It will get executed when the ready state changes. We check two XMLHttpRequest properties readyState and status for specific values. Once these values are attained (readyState of 4 meaning all data has been received and HTTP status of 200) we then use getElementById and change the HTML code between the start and end tags of the P with the id of quotes using this innerHTML property.
Okay, we’ve reached the end of this beginner’s AJAX tutorial. I’ve been talking about AJAX this whole time and I’m sure you’re eager to finally see the AJAX code in action. Below is a link to the sample page where you will see a randomly pulled quote from the PHP AJAX script. Click the Reload Page button to see another quote from the PHP array.
AJAX Tutorial for Beginners: Random Famous Author Quotes
Source Code Download: AJAX Tutorial for Beginners 1 [ No Toolkits ] (Zip)



































