Simple AJAX Example

| 0 Comments

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. So for example, you can refresh results on the page from a form without having to reload the page. The example that I'm going to show you is a name suggestion form. It will display a html form input and will return results from a mysql database that start with whatever char/chars you type in real time.

The form page looks like the following...

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

function showUser(str) {
    xmlhttp=GetXmlHttpObject();
    if (xmlhttp==null)
    {
      alert ("Browser does not support HTTP Request");
      return;
    }
    var url="getNames.php";
    url=url+"?name="+str.value;
    url=url+"&nocache="+Math.random();
    xmlhttp.onreadystatechange=stateChanged;
    xmlhttp.open("GET",url,true);
    xmlhttp.send(null);
}

function stateChanged() {
    if (xmlhttp.readyState==4)
    {
        document.getElementById("nameHint").innerHTML=xmlhttp.responseText;
    }
}

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;
}
</script>
</head>
<body>

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

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


</body>
</html>


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. The code that processes this request is below:



<?php

$name 
striptags($GET
['name']);

if (!empty(
$name)) 
{
    if (
$con mysqlconnect('127.0.0.1''root''1234'))
    {
        if (!
mysql
selectdb('test'))
        {
            echo 
'Could not connect to database';
            exit;
        }
        
$sql sprintf("SELECT name FROM names WHERE name like '%s'"
                        
mysql
realescapestring($name.'%'));
        
$result mysqlquery($sql,$con);
        if (!
$result
        {
            echo 
'Bad Query';
        }
        
$rowCount mysql
numrows($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 striptags 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. Now I 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 mysqlrealescapestring function return the $name variable. The mysqlrealescape_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.

Bookmark and Share

Leave a comment

Recent Entries

Packet Storm ATOM Feed
I was searching around Packet Storm today and wanted to add there new files as a RSS/ATOM feed on my…
PHP Class Passwd
Just for fun, I wrote a short simple class to parse the Linux "passwd" file. The class has functions to…
Simple AJAX Example
I started re-writing a lot of my old code today to use AJAX. AJAX stands for (Asynchronous Javascript and XML)…