I’ve been wanting to have a play with AJAX for ages and had book marked Rasmus’ 30 second AJAX Tutorial so tonight I took 30 seconds, which turned into 30 minutes and had a play.
I’ve extended his example slightly – to include a javascript fix and to make it a bit more browser safe – because I have Opera 7 as my test browser and it doesn’t work, but does for Opera 8 (apparantly).
I’ve put my AJAX Test Bed online – expect to see it change as I play with it and add other functionality. The preliminary code is available in this zip file.
A quick note about AJAX and SEO
Search engines will index the original state of an AJAX page but will be unable to read the dynamic content. If you need the AJAX delivered pages to be indexed you should continue with traditional web building practices.
A quick note about AJAX and Intellectual Property
To get the most out of AJAX the javascript should be used to handle data only – not to make decisions about business rules or anything that could be deemed confidential. Because the javascript can be opened directly from the browser you code can be viewed, copied etc. Ensure that it’s nothing you really care about.
A quick note about AJAX and bookmarks / favorites
Because the content of an AJAX page does not have it’s own url it can’t be recreated from a link in an email, or saved to the users bookmarks or favorites. For this reason you may not want to use AJAX for any data that a user may want to navigate directly to – otherwise you’re going to have to give “permalinks” for your users – but that’s an extra step they may not feel confident with.
My AJAX Test Bed
There are 3 files needed.
- index.php – the page the user views.
- rpc.php – the php script on the server which sends formatted data back to the browser
- js.js – the javascript file which sends the request and receives info from the server
Lets start with the html file (or PHP) which the user sees.
[html]
[Kia Ora] |
[Bula] |
[Bonjour]
[/html]
There’s not much too it, just
- A link to the javascript file
- 3 hyperlinks to get info from the server
- A div which will show the results. The id is very important, and remember, an id can only be used once per page.
In real life there will be so much more but that’s all for now.
Then there’s the PHP script on the server
[php]< ?php
header("Cache-Control: no-cache");
header("Pragma: nocache");
switch($_REQUEST['action']) {
case 'Kia Ora':
$output = "New Zealand";
break;
case 'Bula':
$output = 'Fiji';
break;
case 'Bonjour':
$output = 'France';
break;
}
$output = "foo|{$output} < < " . time() . ' >> ‘;
echo $output;
?>[/php]
I’ve added the time to the output to show how the results aren’t being cached. And I’ve extended the output to include some formatting, but this may be controlled by the javacript as well.
The fields in the output are delimited by the pipe | symbol so if there are more fields to return then you just string them all together. The first part of the output is the name of the id which the output will be inserted into.
And finally, the Javascript
[js]function createRequestObject() {
var ro;
try {
if (window.XMLHttpRequest) ro = new XMLHttpRequest()
else ro = new ActiveXObject(“Microsoft.XMLHTTP”);
}
catch(er) {
alert(‘Ajax is not available for this browser’);
}
return ro;
}
var http = createRequestObject();
function sndReq(action) {
http.open(‘get’, ‘rpc.php?action=’+action);
http.onreadystatechange = handleResponse;
http.send(null);
}
function handleResponse() {
if(http.readyState == 4){
var response = http.responseText;
var update = new Array();
if(response.indexOf(‘|’) != -1) {
update = response.split(‘|’);
changeText(update[0], update[1])
}
}
}
function changeText( div2show, text ) {
// Detect Browser
var IE = (document.all) ? 1 : 0;
var DOM = 0;
if (parseInt(navigator.appVersion) >=5) {DOM=1};
if (DOM) {
var viewer = document.getElementById(div2show)
viewer.innerHTML=text
}
else if(IE) {
document.all[div2show].innerHTML=text
}
}
[/js]
That’s a nice little introduction to AJAX. One of the simpler more straight forward examples that I have seen. By the way, what are you using to show your code view? I like the way it comes out with line numbers and color coding.
Thanks Ryan!
There are a few highlighter options but I discuss the one I use on my Syntax Highlighter for WordPress post.
Awesome tutorial, very easy for a beginner to follow. Unfortunately I’m having trouble understanding what you meant for stringing multiple fields in the output. What would the $output look like if I had a couple divs to output to like div1, div2 and div3?
Oh, maybe use something like | to separate them and then use explode() to split them out.
If your application will be large then you should use one of the big libraries that have been developed.
This example is good for simple requirements and to help you to understand how AJAX works.
“If you need the AJAX delivered pages to be indexed you should continue with traditional web building practices.” There is always a solution. If the initial load of a document is SEO friendly and you use clever addressing, the contents of an AJAX application can be exposed. There’s a post called AJAX and SEO that explains it better.