Starting Ajax - easy example of browser calling up server data
Archive - Originally posted on "The Horse's Mouth" - 2008-09-27 14:21:39 - Graham EllisAjax (Asynchronous Javascript and XML) provides a very neat way for a web page that's displayed on a browser to interact with a web server and replace just part of the page content without the need to reload the whole HTML document or Frame.
It works like this:
1. The original document called up from the server include Javascript which diverts changes to form elements to a local Javascript function
2. The local Javascript function creates an appropriate XMLHttpRequest object, which it sends off to the server.
3. When the response from the server comes back, an event handler at the browser (more Javascript) reads it, and uses it to amend the HTML of the web page.
Ajax isn't really a technology in its own right - rather, it's the combination of a number of other technologies which you'll need to get to grips with to understand how it works. In spare moments over the last 10 days, I've been reading in to and experimenting with Ajax, and I've found that all the examples are over complex as starters - so I've written my own. The complete example is published:
HERE for the web page (.html with Javascript added) sent to the browser and
HERE for the code the runs on the server to provide the web service.
You can try it out here
I have tried - SO hard - to keep this example simple, and complete in just the two files of source I have provided links to above. Here are explanations of some of the more critical bits:
Firstly, the code for the select option menu which triggers the Javascript:
<select onChange="aboutlang(this)">
<option value="None">------</option>
<option value="Perl">Perl</option>
<option value="PHP">PHP</option>
<option value="Python">Python</option>
</select>
Here is some of the Javascript that it triggers (with extra comments added):
function aboutlang(current) {
// Get the value that has just been selected
var lang = current.options[current.selectedIndex].value;
// Make up a request to send to the server
var rqo = new XMLHttpRequest();
// Add in the value that has been entered to the URL
var qs = encodeURIComponent(lang);
var qry = "ajaxcode.php?towhich=" + qs;
// Send the request, saying you want to wait for it to complete
// before carrying on
rqo.open('GET',qry,false);
rqo.send(null);
// Take the entire response, and replace the element that's called
// "result" in your HTML with whatever you got back
document.getElementById("result").innerHTML = rqo.responseText;
// Tell the browser that it has no further actions
return false;
}
The PHP - to run on the server - takes the parameter that's passed in to it and generates a snippet of HTML (in this example):
<?php
$responses = array(
"Perl" => "Perl was written by Larry Wall",
"PHP" => "Rasmus Lerdorf wrote PHP",
"Python" => "From Guido van Rossum came Python");
$send = $responses[$_REQUEST[towhich]];
if ($send == "") {
$send = " --- No information available --- ";
}
$send = "Data retrieved from server at ".date("H:i:s").
" server time<br /><br />"."<b>$send</b>";
print ($send);
?>

Technically, my example isn't really Ajax - it's not asynchronous in that it waits for the server before completing the function at the browser. It's a little more complex, requiring a further function and more logic to handle the events / callbacks of going asynchronous, so that will be lesson 2 rather than lesson one. And also, you could point out to me that I'm not actually sending XML back from the PHP script, but rather just plain ole HTML. Yes - again, that can wait for lesson 2. The example above works on compliant browsers - lesson 3 will tell you how to 'fix' your Javascript to recognise browsers that behave in a somewhat different manner ... for the meantime, I'm going to use the dreadful works "this example is best viewed on Firefox ;-) "

Using Ajax (with PHP on the server side) is covered on our PHP techniques Workshop - a two day course that runs every 8 to 12 weeks, and helps you make the very best of your PHP. If you're interested in learning other aspect of Javascript, please email me graham@wellho.net.
See [here] for the second lesson in this series, where I explain what "Asyncronous" means, why you'll want to use it, and how to implement it in Ajax.