Second Epoch Solutions

 About

 Games

 Sokoban

 AJAX

 LevenshteinMind

 Pangram Composer

 Chess

 IP

 Programming Axioms

 UNIX Millenium Bug

 Contact

 Links

 

 Follow Me


Matt Pullin
GreenCastle

Introduction to AJAX

In this tutorial I will show you a very basic AJAX application. AJAX is a strange word but after going through this tutorial you will understand what AJAX refers to, and hopefully, you can even write your own AJAX applications. Like every skill that is learned, the more you practice it the more complicated applications you will be able to build.

AJAX is not a language. It is more of a web programming trend that started around 2005. Possibly the most famous - and easy to explain - application of AJAX is Google's AutoComplete feature. When you go to one of the main search pages on Google and start to type, you will notice underneath the search bar Google will pop up suggestions of popular searches that start with the letters that you have already typed. This list of suggestions changes very quickly as you are typing, to take into account new letters that you have entered. Clearly the webpage is not refreshing as you are typing in the form... so where does the new information come from?

The answer is AJAX.

AJAX stands for Asynchronous Javascript And XML. AJAX refers to the technique of performing requests behind the scenes, that is, your browser is making requests to the server without "officially" refreshing the page. The information that comes back from these requests is processed via Javascript and used to modify specific elements of the webpage.

The LevenshteinMind game

To illustrate how one goes about building such an application, I'm going to walk you through the construction of a simple browser based game, that works on a principle not unlike Google AutoComplete. I'm going to call it LevenshteinMind.

The Levenshtein distance between two strings A and B is the number of changes (addition, deletion, or substitution) needed to get from string A to string B. The Levenshtein distance between "bee" and "beer" is 1, between "bee" and "deer" is 2, etc.

I've placed a script on my website called levenshteinmind.php. I'm not going to post the contents of this script... all you need to know is this:
1) the script expects to be sent a POST variable called "guess". If this variable is not present the script will return -1.
2) If the POST variable "guess" is not empty the script will return the Levenshtein distance between the "guess" word and some secret word.

This game is in the spirit of the classic game "Mastermind". The player keeps guessing phrases until the Levenshtein distance between his guess and the secret word is 0. This means the player has guessed correctly and wins the game. This game could be quite tiresome if the user had to refresh/submit to the webpage after every guess... so let's do it via AJAX.

Building the Application

We need two things to play this game: a textbox for the user to type the guess, and a feedback area to show him how many characters off the guess is.

?

<input type="text" id="guessField"> <span id="distance">?</span>

Nothing fancy yet. We have created a text field and given it the id "guessField". We've also designated a spot - where the question mark is - for the distance to appear. You'll notice we wrapped the question mark in a <span> tag. This is important because it allows us to reference that spot in the webpage later, by assigning our <span> an id, "distance".

Okay so we want to do something after the user changes the guess. You'd think we would use the onChange event for this, but actually onChange only fires after the field loses focus (i.e. they click somewhere else) so we'll be using onKeyUp instead:

?

<input type="text" id="guessField" onKeyUp="alert('the guess is '+document.getElementById('guessField').value);"> <span id="distance">?</span>

Before we go any further let's just create some space to define a function and call the function within the onKeyUp event. It will make things much neater which will help us very soon:

?

<script type="javascript">
function checkDistance(theGuess){
alert('the guess is '+theGuess+' but we are not doing anything with it - yet');
}
</script>

<input type="text" id="guessField" onKeyUp="checkDistance(document.getElementById('guessField').value)"> <span id="distance">?</span>

Now for the AJAX stuff

We have a function that tells us when the user's guess has changed. Let's add to this function so that it makes an AJAX request to the server, sending along the user's guess to levenshteinmind.php. Try typing in the field in the example below. Don't worry, I will be explaining the new code line by line in a bit.

?

<script language="javascript">
function checkDistance(theGuess){
// define socket
socket = new XMLHttpRequest();
// set up socket events
socket.onreadystatechange=function(){
if(socket.readyState == 4){ // request has returned
if(socket.status == 200){ // request status is OK
document.getElementById('distance').innerHTML = socket.responseText;
if(socket.responseText == '0') alert('You win');
}
}
}
// send request through socket
socket.open("POST","levenshteinmind.php",true);
socket.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
socket.send("guess="+theGuess);
}
</script>

<input type="text" id="guessField" onKeyUp="checkDistance(document.getElementById('guessField').value);"> <span id="distance">?</span>

Have fun trying to guess the secret word! If this game were written entirely in JavaScript on the client side, you'd be able to see the answer by viewing the source of the page. But because our game communicates with a script whose source we cannot see, such a cheat is not available :)

function checkDistance(theGuess){

This is the function we defined that is called whenever there is a new guess

// define socket
socket = new XMLHttpRequest();

The XMLHttpRequest class is the key to how AJAX works. Here we create a new XMLHttpRequest. I like to call mine socket

// set up socket events
socket.onreadystatechange=function(){

An XMLHttpRequest calls onreadystatechange() at various points in the lifetime of the AJAX request. We are about to create a function which we'll assign to our socket's onreadystatechange() in order to track and act on its progress

if(socket.readyState == 4){ // request has returned

The variable readyState reflects the current status of the request.
0 = hasn't been set up
1 = has been set up
2 = has been sent
3 = waiting for the results
4 = finished, and the data has returned

We're only interested in case 4 here

if(socket.status == 200){ // request status is OK

The variable status reflects an HTTP status code.
200 means everything is okay. You've probably heard of 404 - it means 'file not found'.
There are others, but we only care about requests that were OK in this case

document.getElementById('distance').innerHTML = socket.responseText;
if(socket.responseText == '0') alert('You win');

At this point we know that the request was a success. socket.responseText contains the data we got back.

What you do with this data depends on your application. I'm going to display the data (the distance) on the webpage. To do this I first need to obtain a pointer to the area on the webpage we want to put the data in (remember, this is why we named that span 'distance'!) by calling document.getElementById('distance') and then modify its innerHTML property. Modifying innerHTML is a method to change a certain portion of a webpage after the webpage has already finished loading.

Finally I do an alert if the data is '0' because that means the player has won

// send request through socket
socket.open("POST","levenshteinmind.php",true);

open() prepares the socket to do an HTTP request.
We specify POST or GET - POST in this case.
We then specify the URL to make the request for - it's just levenshteinmind.php which happens to be in the same directory. If this were a GET request we'd pass our parameters right here: "levenshteinmind.php?guess="+theGuess

The third parameter determines if the request is asynchronous (can happen in the background while other stuff also happens) or not. It should be set to true

socket.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

setRequestHeader() Modifies the HTTP headers of the request.
POST requests must have 'Content-Type' set.
If this were a GET request we could skip this step

socket.send("guess="+theGuess);

This actually does the POST request, passing one variable: guess.
If we were making a GET request I would have done socket.send(null);

 

And that is all that you need to know to start building AJAX applications!

This example is pretty rough and experienced AJAX users will notice right away some areas that could use improvement - I'm fully aware of these. In fact, here are several possible improvements:

  • You should have a multi-layered method of declaring the XMLHttpRequest to accommodate older versions of IE that don't recognize XMLHttpRequest.
  • You should have better error checking than I did, maybe throw some kind of alert if a non-200 status comes back.
  • You can have your scripts return XML as well, and parse the XML using JavaScript - this is where the X in AJAX comes from.
  • On websites like Facebook and YouTube you see a little animated graphic as the sites make AJAX requests. This is called a throbber and it reassures the user that something is happening. See if you can figure out how you would add a throbber to this application.

As you research the subject on the internet and experiment you will learn more and be able to apply that knowledge to your own future projects. If you had no experience with AJAX previously, I hope I have given you a good starting point.

 

Here is an extended version of the LevenshteinMind game.

 

http://secondepoch.com     © 2005-2017 Second Epoch Solutions