This page covers the three things needed to use AJAX on a Web page. AJAX is JavaScript sending a request to the server to load a Web page (in this case a PHP page). The contents of that page then come back and are used by the JavaScript as text.
Ajax is a combination of HTML, JavaScript and usually PHP (or another server-side language). It can also obtain data from other HTML pages, XML pages or even just text files on the server.
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="sendText();">
<input type="text" size="60" id="suggestion" name="suggestion">
</form>
The form field's ONKEYUP event trigger will start the JavaScript. Every time the user types a letter the JavaScript is triggered.
The JavaScript
Now put some JavaScript into the HEAD of ajax.html. Some of the script runs as the page loads but the functions are called later (one by the event trigger you already put into the HTML):
<script type="text/javascript">
function sendText() {
xmlrequest.open("GET",'autocomplete.php?content='+document.getElementById('fred').value,true);
xmlrequest.send(null);
}
function handleReply () {
if(xmlrequest.readyState==4) {
document.getElementById('suggestion').value=xmlrequest.responseText;
}
}
var xmlrequest=new XMLHttpRequest();
xmlrequest.onreadystatechange=handleReply;
</script>
The first lines to run are the two at the bottom. XMLHttpRequest is used to set up the new connection. The final line of JavaScript creates an event trigger (just like putting onkeyup="fred()" but using a different format. Note that the brackets are left off of the function name. This event trigger calls the second function any time the status of the connection to the server changes. The changes happen as messages pass between browser and server.
The first function (sendText) opens (initialises) the request to the server using the connection handler (XMLHttpRequest) which already exists as xmlrequest. The request is defined inside the brackets and is to run/load a PHP page. It uses GET to send the extra data (from the first form field) to the server as well. The end result will be a URL (or URI) something like this (assuming the user presses the G key):
autocomplete.php?content=g
The second function (handleReply) checks what state the connection is in. If it is readyState 4 this means that data (the Web page) has been received by the browser (from the server) and the data is available to be used. The next line gets that data and puts it into the second form field.
XMLHttpRequest is not supported by Internet Explorer 6 and earlier but most other browsers should have no problem with this code. How to handle this is covered soon.
The PHP page
This page is never seen by the user. It takes the data sent by JavaScript and XMLHttpRequest to the server using GET and performs a MySQL query on a database (you will need this database to test this code so there is a link below to download it). The results of the query are ECHOed to the page and it is this data which is sent to JavaScript for use on the page the user is seeing.
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;
}
}
?>
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 the most likely matches could be sent back for JavaScript to display (as Google does when you type in it's search box). For this example just the first suggestion is ECHOed.
As you can probably see the result of loading this page is that a line of text (a country name) goes to JavaScript and so to the second form field.
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. Make sure you 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 and import the data with PHPMyAdmin. If your database is called something other than test change the $dbname = 'test'; line on your PHP page.
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 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 (using a timer). It could display live messages from other users or allow those users to interact in a collaborative way on a page. It can provide an image slideshow without needing to load all of the images before starting (you just ask for the next image name and change the SRC attribute and the browser will download the new image as usual). 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. There could be a lot of network traffic and a lot of querying of the database if your page is popular so only use Ajax if there are clear benefits.


