Simple AJAX Example

Posted by Tully on Sun 31 January 2010

I started re-writing a lot of my old code today to use AJAX.

AJAX stands for (Asynchronous Javascript and XML) and is a way of making your web applications more interactive.

The below example is a name suggestion form. It will display a html form input and return results from a mysql database that start with whatever char/chars you type in real time.

Form Page

        <title>Simple Ajax Example</title>
        <script type="text/javascript">
        var xmlhttp;

        function showUser(str) {
            if (xmlhttp==null)
            alert ("Browser does not support HTTP Request");
            var url="getNames.php";

        function stateChanged() {
            if (xmlhttp.readyState==4)

        function GetXmlHttpObject() {
            if (window.XMLHttpRequest)
            // code for IE7+, Firefox, Chrome, Opera, Safari
            return new XMLHttpRequest();
            if (window.ActiveXObject)
            // code for IE6, IE5
            return new ActiveXObject("Microsoft.XMLHTTP");
            return null;

        <form name="formName" id="formName">
            <input type="text" name="name" id="name" onKeyUp="showUser(this)">

        <span id="nameHint" name="nameHint"></span>

The form calls getNames.php with the params name=[Input Field Value].

The Input field value is the value of whatever you type into the form
text input.

Processing Code


$name = strip_tags($_GET['name']);

if (!empty($name)) 
    if ($con = mysql_connect('', 'root', '1234'))
        if (!mysql_select_db('test'))
            echo 'Could not connect to database';
        $sql = sprintf("SELECT name FROM names WHERE name like '%s'", 
        $result = mysql_query($sql,$con);
        if (!$result) 
            echo 'Bad Query';
        $rowCount = mysql_num_rows($result);
        while ($row = mysql_fetch_assoc($result)) 
            $names[] = $row['name'];

if (count($names) > 0) 
    echo '<ul>';
    foreach ($names as $name)
        echo "<li>$name</li>";
    echo '</ul>';

As you can see, the getNames.php file first looks at the GET value for the name Parameter. I also have it wrapped in the strip_tags function
which will eliminate the chance of a user entering any kind of tags
that may end up breaking or altering the script. Next, I check to see
if the $name value is empty. The script will not display anything if the $name value is empty or there is no results. Now the script can connect to a mysql server and select the correct DB.

I then write the query using the sprintf function. This allows me to alter multiple
variables in the string. I use the %s for string and have
mysql_real_escape_string function return the $name variable. The
mysql_real_escape_string prepends backslashes to the following
characters "\x00, \n, \r, \, ', " and \x1a".

I now query the database with the $sql string that I just created. I
create the variable rowCount which will return the # of rows returned
from the query. Next we loop through the results and add each name to
the $names variable.

We now have all the results in an array and need to display the result. I first check to see if the array is not empty. I do this by using the count() function on the $names array. If the count is greater then 0 we will display each of the rows returned in a unordered list \<ul> tag.

This is by far the simplest AJAX example. We could have returned the results as JSON and looped through them better in the index.php page. I will write a more technical and more advanced example in the near future.