Skip to content

Taking Ajax further with PHP

Peter's WebDev Workshop

Find this tutorial useful?

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.


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
  • 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).

Ajax tutorial diagram

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.

Please support this work!

There used to be advertising here, but I no longer feel sure that advertising delivers the best experience and truly reflects the values of this site.

Keeping things running, however, is not without financial cost. If you would like to support the time and effort I have put into my tutorials and writing, please
consider making a donation.

Our data

Here’s data.php, which contains our product information.

  1. <?php
  3. // this file just contains our sample data for the application
  4. // you can edit, add to, and delete this data or use a database in a real situation
  6. $products&#91;1]['name'] = 'Big Green monster';
  7. $products&#91;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.';
  8. $products&#91;1]['price'] = 33.99;
  10. $products&#91;2]['name'] = 'Dalmatian';
  11. $products&#91;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.';
  12. $products&#91;2]['price'] = 699.99;
  14. $products&#91;3]['name'] = 'The Latest Gadget';
  15. $products&#91;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.';
  16. $products&#91;3]['price'] = 9999.99;
  18. $products&#91;4]['name'] = 'Purple furry thing';
  19. $products&#91;4]['description'] = 'Hey, it\'s purple and furry. Need we say more? You want one and so does everyone in your street.';
  20. $products&#91;4]['price'] = 10.99;
  23. ?>

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.

  1. <?php
  3. // this is our interface with the user.
  5. require_once('data.php'); // import our data
  7. ?>
  9. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
  10. <html xmlns="" xml:lang="en-gb">
  11. <head>
  12. <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  13. <title>Product information page</title>
  15. <style type="text/css">
  17. /* some really basic styles */
  19. body {
  20.     background-color:#ffffff; font-family:Verdana,sans-serif; font-size:0.8em
  21. }
  23. h1 {
  24.     font-family:'Trebuchet MS',sans-serif; font-size:1.5em
  25. }
  27. </style>
  29. <script type="text/javascript" src="ajaxprodselect.js"></script>
  31. </head>
  32. <body>
  33. <h1>Product information page</h1>
  35. <p>Welcome. Please buy lots of stuff from this website. To find out more about a product, choose it from
  36. the box below.</p>
  38. <!-- we don't actually need a form tag, as it won't be submitted in the normal way in this example -->
  40. <select name="chooseproduct" onchange="selectProduct(this.options[this.selectedIndex]);">
  42. <!-- dummy element, deliberately the value is -1 -->
  43. <option value="-1" selected="selected">---</option>
  45. <?php
  47. // populate the box
  49. foreach ($products as $number => $prod) {
  51.     ?><option value="<?php echo $number;?>"><?php echo $prod&#91;'name'];?></option><?php
  53. } // end foreach
  55. ?>
  56. </select>
  58. <br /><br />
  59. <div id="descriptionarea">Choose a product to see its description here.</div>
  61. </body>
  62. </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.

  1. require_once('data.php'); // import our data
  3. // start the XML document
  5. header('Content-Type: text/xml');
  6. echo '<'.'?'.'xml version="1.0" ?'.'>'."\n";
  7. ?>
  8. <productresponse>
  9. <?php
  11. // if there is no ID, give an error and quit
  13. if (empty($_GET&#91;'prodid'])) {
  15.     ?><requeststatus>ERROR</requeststatus></productresponse><?php
  16.     die();
  18. }
  20. // similarly, if the number is -1, or too big
  22. if ($_GET&#91;'prodid'] == -1 OR ($_GET['prodid'] > count($products)) ) {
  24.     ?><requeststatus>ERROR</requeststatus></productresponse><?php
  25.     die();
  27. }
  29. // otherwise, the request is OK, so let JavaScript know
  31. // then fetch name and description of the product
  32. ?>
  33. <requeststatus>OK</requeststatus>
  35. <productname><?php echo $products&#91;$_GET['prodid']]['name'];?></productname>
  36. <productdesc><?php echo $products&#91;$_GET['prodid']]['description'];?></productdesc>
  37. <productprice><?php echo $products&#91;$_GET['prodid']]['price'];?></productprice>
  39. </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.

  1. var ajaxObject = false;
  3. // this is our object which gives us access
  4. // to Ajax functionality
  7. function selectProduct(productId) {
  9.         if (window.XMLHttpRequest) { // Gecko, KHTML/WebKit, and IE7 apparently
  10.             ajaxObject = new XMLHttpRequest();
  11.             if (ajaxObject.overrideMimeType) {
  12.                 ajaxObject.overrideMimeType('text/xml');
  13.                 // ^ is for older Mozilla-based browsers
  14.             }
  15.         } else if (window.ActiveXObject) { // IE5 or IE6
  16.             try {
  17.         // IE has two methods of calling the object, typical!
  18.                 ajaxObject = new ActiveXObject("Msxml2.XMLHTTP");
  19.             } catch (e) {
  20.                 try {
  21.                     ajaxObject = new ActiveXObject("Microsoft.XMLHTTP");
  22.                 } catch (e) {}
  23.             }
  24.         }
  27.         if (!ajaxObject) {
  28.         alert("Sorry, your browser doesn't support this feature.");
  29.             return false;
  30.         }
  33.         ajaxObject.onreadystatechange = selectProduct_response;
  34.'GET', 'ajax.php?prodid=' + productId.value, true);
  35.         ajaxObject.send(null);
  37.     return true;
  39. } // end selectProduct()
  41. function selectProduct_response() {
  43.     if (ajaxObject.readyState == 4) { // it's finished
  45.         if (ajaxObject.status == 200) { // the HTML request is all OK
  47.             // do the response
  48.             var xmlData = ajaxObject.responseXML.documentElement;
  51.             if (xmlData.getElementsByTagName("requeststatus")[0] != 'OK') {
  52.                 // if <requeststatus> isn't OK, then stop processing
  53.                 alert("Sorry, there was an error.");
  54.                 return;x
  55.             }
  57.             var productName = xmlData.getElementsByTagName("productname")[0];
  58.             // extract product name from the XML
  60.             var productDesc = xmlData.getElementsByTagName("productdesc")[0];
  61.             // same with product description
  63.             var productPrice = xmlData.getElementsByTagName("productprice")[0];
  64.             // and price
  66.             // now we've extracted our data, let's format it
  68.             var divContent = '<strong>Name:</strong> ' + productName + '<br /><br /><strong>Description:</strong> ' + productDesc + '<br /><br /><strong>Price</strong> ' + productPrice;
  70.             // and place it in our div
  71.             document.getElementById('descriptionarea').innerHTML = divContent;
  74.         } // end if status is 200  
  76.         else // if the HTTP code is anything other than 200 OK
  77.         {
  79.                 alert("Sorry, there was an error.");
  80.             return;
  82.         }
  84.     } // end readyState is 4
  86. } // 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:

  1. var productName = xmlData.getElementsByTagName("productname")[0];

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:

  1. if (xmlData.getElementsByTagName("requeststatus")[0] != '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.

Find this tutorial useful?

Like this post?

If you would like to support the time and effort I have put into my tutorials and writing, please consider making a donation.


  1. Ashok wrote:

    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.

    Wednesday, March 14, 2007 at 08:58 | Permalink | Using Internet Explorer Internet Explorer 6.0 on Windows Windows 2000
  2. Tom wrote:

    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!

    Tuesday, March 27, 2007 at 15:11 | Permalink | Using Safari Safari 419.3 on Mac OS Mac OS
  3. mccormicky wrote:

    Thanks for writing this, I needed something like this.

    Tuesday, November 20, 2007 at 07:01 | Permalink | Using Mozilla Firefox Mozilla Firefox on Windows Windows 2000
  4. Bubbila wrote:

    Sweet comprehensive tutorial, just what I have been looking for! Well Pleased…

    Monday, February 11, 2008 at 23:09 | Permalink | Using Internet Explorer Internet Explorer 6.0 on Windows Windows XP
  5. Invader_Zim wrote:

    Thank you so much for your time to write this tutorial. Awesome!

    Friday, October 17, 2008 at 11:05 | Permalink | Using Mozilla Firefox Mozilla Firefox on Windows Windows XP
  6. Alan Gilmore wrote:

    Fantastic content. Just the kind of stuff I need. Thanks so much.


    Friday, October 17, 2008 at 14:29 | Permalink | Using Internet Explorer Internet Explorer 7.0 on Windows Windows XP
  7. Tony Gaspro wrote:

    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.


    Sunday, October 19, 2008 at 19:27 | Permalink | Using Safari Safari 525.20.1 on Mac OS X Mac OS X 10.5.5
  8. Emily wrote:

    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. 🙂

    Saturday, December 6, 2008 at 05:03 | Permalink | Using Mozilla Firefox Mozilla Firefox 3.0.3 on Windows Windows XP
  9. emil wrote:

    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!

    Wednesday, December 17, 2008 at 23:37 | Permalink | Using Mozilla Firefox Mozilla Firefox 3.0.4 on Windows Windows XP
  10. F.P. wrote:

    Thanks! Great tutorial!!

    Friday, January 2, 2009 at 14:47 | Permalink | Using Mozilla Firefox Mozilla Firefox 3.0.5 on Windows Windows XP
  11. Paul wrote:

    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.

    Tuesday, January 13, 2009 at 06:02 | Permalink | Using Mozilla Firefox Mozilla Firefox 3.0.5 on Windows Windows Vista
  12. like ur tuts wrote:


    Thursday, October 29, 2009 at 04:40 | Permalink | Using Google Chrome Google Chrome on Windows Windows XP
  13. John wrote:

    It’s really a good start for me, thank you very much!

    Monday, November 2, 2009 at 08:08 | Permalink | Using Mozilla SeaMonkey Mozilla SeaMonkey 2.0b1 on Linux Linux
  14. Ofer wrote:

    You’ve been my first introduction to Ajax!

    Monday, November 23, 2009 at 02:18 | Permalink | Using Internet Explorer Internet Explorer 8.0 on Windows Windows Vista
  15. egorbrandt wrote:

    thanks, Peter, your tutorials are a great way to share your knowledge: well written, and to the point.

    I enjoyed them very much.

    Thursday, February 18, 2010 at 10:42 | Permalink | Using Mozilla Firefox Mozilla Firefox 3.5.8 on Windows Windows Vista
  16. Nits wrote:

    It runs cool…but i wanna display & update d users info from database….so wht do i do……?

    Tuesday, March 23, 2010 at 08:16 | Permalink | Using Mozilla Firefox Mozilla Firefox 3.6 on Windows Windows XP
  17. Munish wrote:


    Thursday, June 17, 2010 at 14:31 | Permalink | Using Mozilla Firefox Mozilla Firefox 3.6.3 on Windows Windows XP
  18. w wrote:

    Interesting tutorial…

    Sunday, February 26, 2012 at 03:19 | Permalink | Using Safari Safari 534.52.7 on Mac OS X Mac OS X 10.7.2
  19. John wrote:

    I have completed both AJAX tutorials, managed to break them both, and fix them again, with thanks to what I learned here.
    Now I’m off to adapt what I’ve learnt to a real-world scenario.
    Many thanks.

    Thursday, May 2, 2013 at 01:11 | Permalink | Using Google Chrome Google Chrome 26.0.1410.64 on Windows Windows 7

19 Trackbacks/Pingbacks

  1. […] Taking Ajax further with PHP […]

  2. […] Ready to take Ajax further? I’ve got a followup tutorial. This was written by Peter. Posted on Wednesday, September 27, 2006, at 5:09 pm. Filed under […]

  3. 50 Excellent AJAX Tutorials | Tutorials | Smashing Magazine on Thursday, October 16, 2008 at 22:46

    […] Taking AJAX Further with PHP Following up on the preceding introduction, this post goes a bit further. […]

  4. Useful AJAX Tutorials | Neurosoftware web dev on Friday, October 17, 2008 at 07:58

    […] Taking AJAX Further with PHP Following up on the preceding introduction, this post goes a bit further. […]

  5. on Friday, October 17, 2008 at 12:14

    Taking Ajax further with PHP…

    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 a…

  6. 50 Excellent AJAX Tutorials | Web Burning Blog on Saturday, October 18, 2008 at 09:05

    […] Taking AJAX Further with PHPFollowing up on the preceding introduction, this post goes a bit further. […]

  7. 50 Excellent AJAX Tutorials | Evolution : weblog on Friday, October 31, 2008 at 05:22

    […] Taking AJAX Further with PHP Following up on the preceding introduction, this post goes a bit further. […]

  8. 50 Excellent AJAX Tutorials « Rohit Dubal on Monday, February 16, 2009 at 10:43

    […] Taking AJAX Further with PHP Following up on the preceding introduction, this post goes a bit further. […]

  9. […] Taking AJAX Further with PHP Following up on the preceding introduction, this post goes a bit further. […]

  10. […] “Taking AJAX Further with PHP”: Following up on the preceding introduction, this post goes a bit further. […]

Post a Comment

On some sites, you must be logged in to post a comment. This is not the case on this site.
Your email address is not made public or shared. Required fields are marked with *.

Posting a comment signifies you accept the privacy policy.
Please note — usually your comment will appear straight away but sometimes it will be held for approval (this is due to the spam filter). If your comment is waiting to be approved, please don’t post it again! It will appear eventually.