Ajax Project - Form Entry Suggest

Didn't find what you want? Try our search

The projects and demos in this section all use a MySQL database which holds a single table contact with records from a simplified contact manager application.

Have a look at the records in the sortable data grid demo. We are going to use those records to populate an input fields on a form, using Ajax. This is similar to the 'Google Suggest' application.

The Telephone Numbers are:
ANNE01234 005134
ATTORNEY01122 34567
BOSS01777 009123
FAYE01223 009134
FRED01334 003456
ROD011-111-1111000
SUE01555 9999
THERAPIST01555 9999

Start to type one of these Telephone Numbers into the field on the form below. Notice that, with each letter typed, a dropdown list of clickable selections opens beneath the entry field. Click on a link in the list to load the associated telephone number into the form.

Tel Number: 

How it works

Each time you type a character into the Telephone Number field, a Javascript event handler is called using the onKeyUp event. The event handler reads the characters entered in the field thus far, and sends that information to the server via an Ajax call.

A server routine then carries out a SQL query on the database table contact, returning the matching fields.

A Javascript routine called the response handler then uses this information to populate the drop down box and make it visible.

The Code

First, let's see the code for the form itself:

<form name="schform" onReset="this.telno.value='';getagenttel()"> <table> <tr><td>Tel Number:</td><td><input id="agtel" type="text" name="telno" onKeyUp="getagenttel();">&nbsp; <input type="reset" value="Clear Entry Field"></td></tr> </table> </form> <div id="hiddenDIV2" style="position:relative; top: -22px; left: 85px;width: 200; visibility:hidden; background-color:white; border: 1px solid black;"> </div>

Note that the Telephone Number field contains the onKeyUp function to trap for keystrokes. Next up is the event handler for catching these keystrokes:

var url = "getagenttel.php?param="; function getagenttel() { var idValue = document.getElementById("agtel").value; var myRandom = parseInt(Math.random()*99999999); // cache buster http.open("GET", url + escape(idValue) + "&rand=" + myRandom, true); http.onreadystatechange = handleHttpResponse; http.send(null); }

The code to instantiate an XMLHTTPRequest is well covered elsewhere on this site, so we'll not do so again here; suffice to say that http is our already-existing XMLHTTPRequest object.

Firstly, we read the string typed thus far into the variable idValue, then we form a 'GET' request by appending this value as a parameter to the URL stored in our variable url. This URL contains the address of the server-side script which will process our Ajax request.

The variable myRandom contains a random number which is also appended to the URL as a parameter, and helps us to ensure we receive fresh server data rather than data from our browser's cache. This technique is described elsewhere on the site in the article on Cache Busting with Javascript.

We define the javascript routine which will handle the server's response as handleHttpResponse, but before we look at that' let's see what happens at the server by examining the code for getagenttel.php:

[ ... DB connection code here ... ] if(strlen($param)>0){ $result = mysql_query("SELECT * FROM contact WHERE ContactTel LIKE '$param%'"); if(mysql_num_rows($result)>0) { while($myrow = mysql_fetch_array($result)){ $agenttel = $myrow["ContactTel"]; $agentid = $myrow["ContactID"]; $textout .= "<table><tr style=\"border: 0px solid black\"> <td style=\"border: 0px solid black; padding: 0px 10px 0px 10px\"> <a href=\"javascript:loadrecord('".$agenttel."')\">" .$agentid."</a></td> <td style=\"border: 0px solid black; padding: 0px 10px 0px 10px\">" .$agenttel."</td></tr></table>"; } } else { $textout=""; } } echo $textout;

Here we perform a SELECT query on the server to collect any records with Contact ID values matching the typed entry. If there is exactly one match, that is, if we have identified a unique result, we pass it back as a comma-delimited string. Otherwise, we simply pass back a comma-delimted string which is empty save for echoing back the original parameter (the string typed in thus far).

OK, let's see how handleHttpResponse deals with this information:

function handleHttpResponse() { if (http.readyState == 4) { document.getElementById("hiddenDIV2") .style.visibility="visible"; document.getElementById("hiddenDIV2") .innerHTML=http.responseText; } } function loadrecord(record) { document.schform.telno.value = record; }

Here we can see how the text returned from the server is returned as a table, which is used to populate the popup box. The helper function loadrecord(record) is called when one of the links in the table is clicked, loads the appropriate telephone number into the data entry field.


Before using any software from this site, please see the Terms



9 Users Online.

All of the code and information on this site is provided free of charge (but without warranty).
If you feel that the site has been useful, you may care to donate a little toward the running of the site and the development of further projects?