Ajax Project - Populating a Form
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 the input fields on a form, using Ajax.
The Contact IDs are:
ANNE, ATTORNEY, BOSS, FAYE, FRED, ROD, SUE, THERAPIST
Start to type one of these Contact IDs into the relevant field on the form. Notice that, as soon as the application can uniquely identify the record, it populates the relevant fields - including the one in which you're typing.
How it works
Each time you type a character into the Contact ID 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. If it finds exactly one record whose Contact ID begins with the characters already input, it then returns the fields belonging to that record.
A Javascript routine called a response handler then uses this information to populate the form fields.
The Code
First, let's see the code for the form itself:
Note that each field has been assigned an id. We shall use these ids in our Javascript routines to manipulate the data values that the fields contain. Also note that the Contact ID field contains the onKeyUp function to trap for keystrokes. Next up is the event handler for catching these keystrokes:
var url = "getagentids.php?param=";
function getagentids() {
var idValue = document.getElementById("agid").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 getagentids.php:
[ ... DB connection code here ... ]
if(strlen($param)>0){
$result = mysql_query("SELECT * FROM contact
WHERE ContactID LIKE '$param%'");
if(mysql_num_rows($result)==1) {
while($myrow = mysql_fetch_array($result)){
$agentname = $myrow["ContactFullName"];
$agenttel = $myrow["ContactTel"];
$agentsal = $myrow["ContactSalutation"];
$agentid = $myrow["ContactID"];
$textout .= $agentname.",".$agentsal.",".$agenttel.",".$agentid;
}
} else {
$textout=" , , ,".$param;
}
}
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) {
results = http.responseText.split(",");
document.getElementById('agfn').value = results[0];
document.getElementById('agsal').value = results[1];
document.getElementById('agtel').value = results[2];
document.getElementById('agid').value = results[3];
}
}
Here we can see how the text returned from the server is split into an array called results[]. The values of the array elements correspond to fields on the form, and are used to populate these fields. If no unique match has been found, the Contact ID field in which we are typing is simply re-populated with it's current value, and the other fields receive null values; to the user, nothing seems to have happened. When a unique match is found, the fields are populated appropriately, inclding the Contact ID field in which we are typing.
In this demo, the form serves no real purpose. In a real-world application it could, for instance, allow a user to locate a contact record and then modify that contact's data before re-submitting the changes to the database - and all without a page refresh.
Before using any software from this site, please see the Terms
|