Get a taste of AJAX with PHP

Some of you may have heard of Ajax, while some may have not. The truth of the matter is that Ajax (Asynchronous JavaScript and XML) is a technology to be followed. Furthermore, a technology to be used! To give a little background about it, let’s see what wikipedia has to say about it: “term describing a web development technique for creating interactive web applications using a combination of: HTML (or XHTML) and CSS for presenting information; The Document Object Model manipulated through JavaScript to dynamically display and interact with the information presented; and The XMLHttpRequest object to exchange data asynchronously with the web server. (XML is commonly used, although any text format will work, including preformatted HTML, plain text, and JSON)”.

For Gmail (Google Mail) or GMaps (Google Maps) users, you have already experienced the power of Ajax. Notice how when you switch from page to page in GMail the browser page does not reload? That’s the power of Ajax.

In this post, I’ll give you an introduction to Ajax using a yet in beta stage, but very powerful open source PHP library called XAJAX. I’ll get right down to the coding (more information about this library can be obtained from its sourceforge site.)

As an example, I’ll develop the classic Country / State combo box combination. Normally, if we wanted the State combo to be updated by the current selected country, we would make one of two choices:

  • Use Javascript by sending all countries and their respective provinces to the client browser, and update State combobox choosing those states that belong to the selected country.
  • Reload the page when a different country has been selected, including only that country’s states in the State combo box.

With Ajax, we’ll do none of those. We’ll have the list of states per country on a server-side PHP script. When the country selection changes, we’ll use Xajax to update the list of available states based on the country selection. To simplify, I’ll do all this on the same PHP file.

We start by including the xanax library, and declaring a PHP function that will be called via Ajax when the country selection changes.

require_once(dirname(__FILE__) . '/');

function setCountry($countryCode)
        $provinces = array();

                case 'AR':

                        $provinces['BA'] = 'Buenos Aires';
                        $provinces['CO'] = 'Cordoba';
                        $provinces['SL'] = 'Salta';
                        $provinces['SF'] = 'Santa Fe';


                case 'US':

                        $provinces['CA'] = 'California';
                        $provinces['WA'] = 'Washington';


        $objResponse =& new xajaxResponse();

        if (count($provinces) > 0)
                $objResponse->addScript("document.getElementById('province').disabled = false;");
                $objResponse->addScript("document.getElementById('province').options.length = 0;");

                foreach ($provinces as $id => $province)
                        $objResponse->addScript("addOption('province','" . $province . "','" . $id . "');");
                $objResponse->addScript("document.getElementById('province').options.length = 0;");
                $objResponse->addScript("addOption('province','-- Select a Country first -','');");
                $objResponse->addScript("document.getElementById('province').disabled = true;");

        return $objResponse->getXML();

The first few lines are quite easy to follow. The first interesting thing that we see here is when we start by creating the Xajax response ($objResponse =& new xajaxResponse();) After that, if there are states to be inserted, we enable the state control, reset the state combo box (by setting its option length to 0), and for each state we call a client side javascript function called addOption() that will insert the specified option in the combo box. If no states are to be inserted, then we empty the combo box, inserting only a dummy option, and disable the element.

Now, let’s see the next few server-side lines of code:

$xajax =& new xajax();



Here, we instantiate the main xajax handler, registering the function we’ve just created, and telling xajax to process any request. From here on, all the remaining code is client side (HTML). What we need to pay special attention to is the client side javascript function we already mentioned, which is included here, and the insertion of xajax generated javascript code, all of this is done within the header tag of the HTML document:

<script type="text/javascript">
function addOption(selectId, txt, val)
        var objOption = new Option(txt,val);

// -->

Finally, the code that dispatches xajax when the country selection changes:

<select name="country" id="country" onchange="xajax_setCountry(document.getElementById('country').value);">
<option value="">-- Select a Country --</option>
<option value="AR">Argentina</option>
<option value="US">United States</option>

You can see the code working here, and download the source file here.

Related posts:

  1. MSN Search API PHP Client

Leave a Comment

8 Comments to "Get a taste of AJAX with PHP"

  1. Jan042006 at 8:35 pm

    Gaurav Arora [Visitor] wrote:

    Thank you so much for the article and the example. I had to make a signup form for a client which pulled data from a database of countries, states and cities. Your example was most useful…infact it was THE only thing I needed to read to accomplish the task.

    Once again, thanks a lot.

  2. Jan192006 at 12:31 pm

    Sérgio Berlotto [Visitor] wrote:

    Great syntax higlhither…
    So good !

    I will install on my site…

  3. May122006 at 9:28 am

    derek [Visitor] wrote:

    Very interesting and professional site! Good luck!

  4. Jun082006 at 4:20 pm

    elvisman [Visitor] wrote:

    I’m not sure if ajax is a technology to be followed… check this:

  5. Jul252006 at 9:50 am

    Diego Juritz [Visitor] wrote:

    Mariano: useful as usual!
    Great example.
    I had tried it and it worked!

  6. Sep142009 at 4:51 am

    Eva [Visitor] wrote:

    Hi, I’m beginner with PHP. I just downloaded xajax.ini.php files and your example code. it can not work, and there is no error. I don’t know why. Can you give the entire code including the php files that you used. Thank you very much.
    Best wishes.

  7. Sep142009 at 7:55 am

    mariano.iglesias [Member] wrote:


    This is a very old post (4+ years) so I really don’t have the source code I used back then.

    These days I recommend to anyone who wants to develop PHP based applications to use a framework, such as CakePHP:

    It greatly simplifies the whole development cycle.

    You should try it out.

  8. Nov092009 at 6:20 am

    stolen [Visitor] wrote:

    hi to everybody, pls help me for this problem, i m new in php…..

    i want show message in this ajax function
    function saveClass($className)
    global $db_obj;
    $objResponse = new xajaxResponse();
    $mess = ”;

    $sql=”select * from class where classname=’”.$className.”‘”;
    $rres = $db_obj->query($sql);
    if(mysql_num_rows($rres )>0)
    //i want show message here
    $_SESSION['alert']= ” “;
    $sql =”insert into class (className) values(‘”.$className.”‘)”;
    $insert_user_query = $db_obj->execute($sql);
    return $objResponse->getXML();


    //pls help this problem

Powered by Wordpress and MySQL. Clauz's design for by Cricava