
First of all, I have to apologise. It's been literally two months since my last post in this series, and it's been more than that since I last looked at Ajax in PHP. OK, I might admit it, it was this comment that motivated me to pick up this series again. Oh, that and I'm now on the half term break, so I'm finally getting round to some things that have been on the back burner for a long time.
In our last Ajax tutorial, we got started with Ajax using PHP and made our first Ajax application.
Today, we're going to take Ajax a little further, by building a little application where our user selects a product from a pop-up list, and then we do a little Ajax dance to get some product details (and an image) and display them in a box below. We'll be making our own little XML schema which we'll use to pass information between the JavaScript in the user's browser and our PHP script on the server.
Requirements
For this tutorial, you'll need the following (and in brackets, I'll show you what I'll be using):
- A web server running PHP (I'm using PHP 5, but it might work on PHP 4).
- A decent browser (I'll be using Firefox 2.0.0.1).
- A decent text editor and/or IDE that supports Unix line breaks if you download my set of files (I'm using the best web development IDE in the world, Quanta).
- Some patience, time, determination and enough hair to rip out when the JavaScript is going wrong (check, check, check).
Also highly recommended, but not required, is the Firebug extension for Firefox, as it makes checking and debugging your JavaScript a lot easier.
All code in this tutorial is released under the Modified BSD Licence.
You might want to download yourself the finished project now, so you can see how it works and if you're not rewriting it yourself and just stepping through my code.
Download .zip
Download .tar.gz
Download .tar.bz2
What we're doing
Diagrams are always good, so let's briefly look at what we'll be doing (click to enlarge, or grab the PDF).
That's roughly how our system is going to work.
Our list of products that will appear in the <select> list will be populated by PHP on the pageload and for this tutorial, the product data that we'll be using will be hard-coded into PHP. There's no reason why you couldn't populate the list and fetch product details using a database, but to keep it simple, we'll stick with a set list for this tutorial. We will write it so that it's easily modifiable, though.
Our data
Here's data.php, which contains our product information.
-
<?php
-
-
// this file just contains our sample data for the application
-
// you can edit, add to, and delete this data or use a database in a real situation
-
-
$products[1]['name'] = 'Big Green monster';
-
$products[1]['description'] = 'If you want a monster, look no further than a Big Green one. Big Green have over 40 years experience making top-quality monsters, and at low, low prices.';
-
$products[1]['price'] = 33.99;
-
-
$products[2]['name'] = 'Dalmatian';
-
$products[2]['description'] = 'A white dog with black spots is just what you need. But don\'t take our word for it, speak to our happy customer.';
-
$products[2]['price'] = 699.99;
-
-
$products[3]['name'] = 'The Latest Gadget';
-
$products[3]['description'] = 'Can you live without The Latest Gadget? Probably, yes, but you don\'t have to! Buy it now and we guarantee you will be satisfied. Not an actual guarantee.';
-
$products[3]['price'] = 9999.99;
-
-
$products[4]['name'] = 'Purple furry thing';
-
$products[4]['description'] = 'Hey, it\'s purple and furry. Need we say more? You want one and so does everyone in your street.';
-
$products[4]['price'] = 10.99;
-
-
-
?>
OK, fairly simple. From now on, we need to make sure all our PHP files include() or require() this data file.
Our interface
Here's index.php, our main interface with the user.
-
<?php
-
-
// this is our interface with the user.
-
-
require_once('data.php'); // import our data
-
-
?>
-
-
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-gb">
-
<head>
-
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
-
<title>Product information page</title>
-
-
<style type="text/css">
-
-
/* some really basic styles */
-
-
body {
-
background-color:#ffffff; font-family:Verdana,sans-serif; font-size:0.8em
-
}
-
-
h1 {
-
font-family:'Trebuchet MS',sans-serif; font-size:1.5em
-
}
-
-
</style>
-
-
<script type="text/javascript" src="ajaxprodselect.js"></script>
-
-
</head>
-
<body>
-
<h1>Product information page</h1>
-
-
<p>Welcome. Please buy lots of stuff from this website. To find out more about a product, choose it from
-
the box below.</p>
-
-
<!-- we don't actually need a form tag, as it won't be submitted in the normal way in this example -->
-
-
<select name="chooseproduct" onchange="selectProduct(this.options[this.selectedIndex]);">
-
-
<!-- dummy element, deliberately the value is -1 -->
-
<option value="-1" selected="selected">---</option>
-
-
<?php
-
-
// populate the box
-
-
foreach ($products as $number => $prod) {
-
-
-
} // end foreach
-
-
?>
-
</select>
-
-
<br /><br />
-
<div id="descriptionarea">Choose a product to see its description here.</div>
-
-
</body>
-
</html>
The Ajax backend
Here's our PHP file that will act as our backend. It's the script JavaScript calls behind the scenes to get the data. As you can see, we have our own XML setup going on below, which I'll explain in a minute.
-
require_once('data.php'); // import our data
-
-
// start the XML document
-
-
?>
-
<productresponse>
-
<?php
-
-
// if there is no ID, give an error and quit
-
-
-
?><requeststatus>ERROR</requeststatus></productresponse><?php
-
-
}
-
-
// similarly, if the number is -1, or too big
-
-
-
?><requeststatus>ERROR</requeststatus></productresponse><?php
-
-
}
-
-
// otherwise, the request is OK, so let JavaScript know
-
-
// then fetch name and description of the product
-
?>
-
<requeststatus>OK</requeststatus>
-
-
-
</productresponse>
Our XML schema here is made up of the following:
productresponse is the root tag, and is only really used here as a container.
requeststatus lets JavaScript know whether the request was OK, or failed, identified by ERROR or OK. (If there is an error, that's it - the end of the XML document. We won't bother including the tags below).
productname contains the product name (funnily enough).
productdesc contains the product description.
productprice is for the price.
If you've got all the files in place so far, try browsing to ajax.php. If you're using a decent browser, you should get a nice syntax-highlighted XML tree (nice for debugging). You'll notice that you've got an error here, and rightly so - you didn't specify a product ID!
Try going to ajax.php?prodid=1. That's better. You should see the data in ourtags. That's our fully formed XML document that JavaScript will have the job of parsing and formatting. Sounds like fun...
The JavaScript
Now, finally, the hardest part of the whole exercise - the JavaScript that actually makes sense of the XML and displays it in our box. Bear with me here, let's just get the code down here then I'll explain what we're doing.
-
var ajaxObject = false;
-
-
// this is our object which gives us access
-
// to Ajax functionality
-
-
-
function selectProduct(productId) {
-
-
if (window.XMLHttpRequest) { // Gecko, KHTML/WebKit, and IE7 apparently
-
ajaxObject = new XMLHttpRequest();
-
if (ajaxObject.overrideMimeType) {
-
ajaxObject.overrideMimeType('text/xml');
-
// ^ is for older Mozilla-based browsers
-
}
-
} else if (window.ActiveXObject) { // IE5 or IE6
-
try {
-
// IE has two methods of calling the object, typical!
-
ajaxObject = new ActiveXObject("Msxml2.XMLHTTP");
-
} catch (e) {
-
try {
-
ajaxObject = new ActiveXObject("Microsoft.XMLHTTP");
-
} catch (e) {}
-
}
-
}
-
-
-
if (!ajaxObject) {
-
alert("Sorry, your browser doesn't support this feature.");
-
return false;
-
}
-
-
-
ajaxObject.onreadystatechange = selectProduct_response;
-
ajaxObject.open('GET', 'ajax.php?prodid=' + productId.value, true);
-
ajaxObject.send(null);
-
-
return true;
-
-
} // end selectProduct()
-
-
function selectProduct_response() {
-
-
if (ajaxObject.readyState == 4) { // it's finished
-
-
if (ajaxObject.status == 200) { // the HTML request is all OK
-
-
// do the response
-
var xmlData = ajaxObject.responseXML.documentElement;
-
-
-
if (xmlData.getElementsByTagName("requeststatus")[0].firstChild.data != 'OK') {
-
// if <requeststatus> isn't OK, then stop processing
-
alert("Sorry, there was an error.");
-
return;x
-
}
-
-
var productName = xmlData.getElementsByTagName("productname")[0].firstChild.data;
-
// extract product name from the XML
-
-
var productDesc = xmlData.getElementsByTagName("productdesc")[0].firstChild.data;
-
// same with product description
-
-
var productPrice = xmlData.getElementsByTagName("productprice")[0].firstChild.data;
-
// and price
-
-
// now we've extracted our data, let's format it
-
-
var divContent = '<strong>Name:</strong> ' + productName + '<br /><br /><strong>Description:</strong> ' + productDesc + '<br /><br /><strong>Price</strong> ' + productPrice;
-
-
// and place it in our div
-
document.getElementById('descriptionarea').innerHTML = divContent;
-
-
-
} // end if status is 200
-
-
else // if the HTTP code is anything other than 200 OK
-
{
-
-
alert("Sorry, there was an error.");
-
return;
-
-
}
-
-
} // end readyState is 4
-
-
} // end selectProduct_response
Dissecting the JavaScript
You should be able to decipher the vast majority of this already. If you've been through the first tutorial (and you certainly should have), you should understand exactly what we're doing with the basic Ajax stuff.
The new and important bit here are the lines like this:
-
var productName = xmlData.getElementsByTagName("productname")[0].firstChild.data;
All that's really saying is this:
- Go to the XML document and fetch me all the elements with the tag name 'productname'.
- Now get me the first instance of that tag (that's the [0] bit)
- Go to the first child (meaning the stuff inside that tag)
- Fetch me the content of the stuff inside that tag
We do that for the name, description and price and each time put that information in a variable.
We then just concatenate these variables together with some HTML formatting and line breaks, and that's what is going inside our div.
We put that in our div, and we're done!
You might also notice the line:
-
if (xmlData.getElementsByTagName("requeststatus")[0].firstChild.data != 'OK')
It's exactly the same idea, but instead of putting the content of the requeststatus tag into a variable so we can use it later, we just check to see if it isn't 'OK'. And if it isn't, we throw an error dialogue box.
It works!
At this point, our example works very well. Very very well. If you head over to index.php, you should be able to simply select a product from the list and have the description pop into the correct box within a second or two.
It might not seem very impressive for the level of work - and in fact, we could have done this without XML, but now that you've got some basic XML parsing with JavaScript ability, you can move on to cooler things with Ajax.
I could go on and extend this application some more, but this is already a monster post and it's about time I signed off this tutorial. We may well be returning to this project at a later date to add some more functionality to it, but I can't guarantee when that will be.
Feedback is the key
This tutorial took an insane amount of time to write. Almost a whole afternoon. Actually, you have to plan it, write the code, then write the tutorial, debug the code, fix the code, break the code, rewrite bits of the tutorial and check everything works.
And that takes time.
All I ask of you is that if you read this and liked it, or if you didn't, or if you just read it, to leave a comment below. It makes all the effort worthwhile.
Anyway, thanks for reading thus far and I look forward to next time!
Icon from Oxygen icon set, CC BY-NC 2.5.

this is one and only & very nice tutorial, which i have found in net. By this i can able to write my own ajax program.
thank u very much.
Ashok
Awesome, prior to reading this article the process of adding some ajax to my php sites was a pretty nebulous to say the least. This gives me a great jumping off point. Thanks a bunch!
Thanks for writing this, I needed something like this.
Sweet comprehensive tutorial, just what I have been looking for! Well Pleased…
Thank you so much for your time to write this tutorial. Awesome!
Fantastic content. Just the kind of stuff I need. Thanks so much.
Alan
Excellent tutorial. I check out the basic PHP/AJAX tut, and after going over it, immediately went through this one.
Your tutorials are clear and concise. Will be letting friends know about these two.
Cheers.
Thanks a billion for this tutorial.. i have been trying learn ajax. so far i cant really understand it. But your is a simple and detail one which i can understand and now i know how to write it already.
Once again thank you for your time in writing this tutorial.
awesome stuff man! you really helped me into ajax and I will not try to rewrite my blog into ajax and xml stuff!
thanks dude!
Thanks! Great tutorial!!
Thanks a great deal for these two tutorials! The instructions are very clear and well written, an excellent jumping point to start my training into what I can do with AJAX.
I look forward to reading the next installment.