Introducing AJAX

This page covers the three things needed to use AJAX on a Web page.

The XHTML

Put this into the BODY of a properly structured HTML page called ajax.html:

            
<form name="thisform">
	<input type="text" size="40" id="fred" name="fred" onkeyup="ajax();">
	<input type="text" size="60" id="suggestion" name="suggestion">
</form>            
        

The form field's ONKEYUP event trigger with start the JavaScript which reads the first field's content and then fills in a response in the second. Every time the user types a letter the JavaScript is triggered resulting in something being put into the second text box. The page does not reload so the only thing which changes is the second field.

The JavaScript

Now create a JavaScript function in the HEAD of ajax.html. This script will be called by an event later:

        
<script type="text/javascript">
    function ajax() {
    
        var request=new XMLHttpRequest();
        
        request.onreadystatechange=function() {

            if(request.readyState==4) {
                document.getElementById('suggestion').value=request.responseText;
            }
        }
        
        request.open("GET","autocomplete.php?content="+document.getElementById('fred').value,true);
        request.send(null);
        
    }
</script>        
        

This might look complicated (especially if you didn't practice your JavaScript much) but it isn't.

The key to the code is a connection with the PHP (or ASP) server. XMLHttpRequest makes the connection. The next line makes things happen any time the connection to the server changes. The changes happen as messages pass between browser and server.

The next line is an IF statement which checks on what state the connection is. The readyState 4 means that data has come from the server so the data is available to be used. The next line gets that data and puts it into an XHTML element called suggestion (you will create that soon).

The last two lines use the connection to the server to open (initialise) and send the request to the server. The request is to run/load a PHP page. It uses GET to send data from an element on the XHTML page to the server for processing by the page.

XMLHttpRequest is not supported by Internet Explorer 6 and earlier and you might want to build in an IF statement to check for whether the browser supports it. This is covered on the next page of this tutorial.

The PHP page

This is never seen by the user. It takes the data sent by JavaScript using GET and performs a MySQL query on a database. Put this into a PHP page called autocomplete.php:

    
<?php
if (!$_GET['content']=="") {
        
	$sofar=$_GET['content'];
            
	$mysqlusername="test";
	$mysqlpassword="test";
	mysql_connect(localhost, $mysqlusername, $mysqlpassword) or die ('Error connecting to mysql server: '.mysql_error());
	$dbname = 'test';
	mysql_select_db($dbname) or die ('Error selecting specified database on mysql server: '.mysql_error());
                
	$suggestionquery="SELECT Name FROM Country WHERE Name LIKE '$sofar%' LIMIT 1";
                
	$suggestionresult=mysql_query($suggestionquery) or die('aaagh: '.mysql_error());
                
	$suggestionline=mysql_fetch_array($suggestionresult);
                
	$suggestion=$suggestionline['Name'];
                
	if ($suggestion==""){
		echo "There are no matching countries - have you spelled this correctly?";
	} else {
		echo $suggestion;
	}
}
?>
        

JavaScript will use XMLHttpRequest to load autocomplete.php every time the user types a letter. As with any PHP page when it is requested the server interprets the page and the only content after processing should be what is ECHOed. The PHP page does not load in the browser, instead it goes to the JavaScript function and can be used by it. As you can see the result is that a line of text goes to the second form field. There is a lot of network traffic and a lot of querying of the database.

You should be able to understand the PHP. It connects to MySQL and asks for a list of countries which match the letters typed so far. A list of most likely matches could be sent back for JavaScript to display (as Google does when you type in the search box). For this example just the first suggestion is ECHOed to the HTML page and this is then sent to the JavaScript rather than displayed.

Tying it all together

Although only one thing is new to you (XMLHttpRequest) you may struggle to understand this without seeing it in action. To do that you need a Web server with PHP and MySQL. Upload both pages.

You also need a database called test. In it a table called Country. In that table is a field called Name with country names in it. You can create this in PHPMyAdmin or you can download a suitable database with lots of real data in it from the MySQL site..

Now load ajax.html in a browser (not IE 6!) and type a letter in the first field.

Conclusion

AJAX is explained on just one page because that is all there is to learn (OK there are two more pages but they are not totally necessary). The rest is up to you. You can adapt the JavaScript, XHTML or PHP/MySQL to make this example do almost anything. You are only limited by your knowledge of the three technologies involved (XHTML, JavaScript and PHP/MySQL) and your imagination.

AJAX could be used to allow interactive games or learning materials. It could do live changes of page content to show up-to-date scores or news. It could display live messages from other users or allow those users to interact in a collaborative way on a page. Most importantly it can do things which no one else has thought of yet so you could be the first to come up with the next big use for AJAX.