- Menu scripts
- Window scripts
- Calendar scripts
- Gallery scripts
- Form widgets
- Tab view scripts
- Table widgets
- Drag and drop
- Folder trees
- Tooltips
- AJAX scripts
- Content Effects

- Misc scripts
- Javascript games
- Chess widgets
- DHTML Suite
- Resources
- cbolson.com
Download AJAX client lookup
Licensing
This script is distributed under the LGPL open source license.
Commercial licenses are also available. Some of these licenses also includes personal e-mail support for up to 1 year.
PHP
This script requires PHP. You can also other server side languages if you rewrite the code for getClient.php(See below)
Put this into your <HEAD> section
Put this into your <BODY> section
Download Javascript file
I have used the Simple Ajax Code Kit library(SACK) for this script. I have made a copy available for download here.
Put ajax.js in a subfolder called "js" or change the path to the file in the code above(i.e. <script type="text/javascript" src="js/ajax.js"></script>)
SQL
I have created a simple mySql table for this example. You can copy the queries from here
File for client lookup
A php file getClient.php is used in this script. This PHP file is called by Ajax when a new client ID is entered into the first text field. It will connect to the database and try to find a client with the entered client ID. If one is found, it will send data back to AJAX. These data will evalulated by our main script.
The getClient.php file looks like this:
<?php
/* Replace the data in these two lines with data for your db connection */
$connection = mysql_connect("host","username","password");
mysql_select_db("databaseName",$connection);
if(isset($_GET['getClientId'])){
$res = mysql_query("select * from ajax_client where clientID='".$_GET['getClientId']."'") or die(mysql_error());
if($inf = mysql_fetch_array($res)){
echo "formObj.firstname.value = '".$inf["firstname"]."';\n";
echo "formObj.lastname.value = '".$inf["lastname"]."';\n";
echo "formObj.address.value = '".$inf["address"]."';\n";
echo "formObj.zipCode.value = '".$inf["zipCode"]."';\n";
echo "formObj.city.value = '".$inf["city"]."';\n";
echo "formObj.country.value = '".$inf["country"]."';\n";
}else{
echo "formObj.firstname.value = '';\n";
echo "formObj.lastname.value = '';\n";
echo "formObj.address.value = '';\n";
echo "formObj.zipCode.value = '';\n";
echo "formObj.city.value = '';\n";
echo "formObj.country.value = '';\n";
}
}
?>
Comments
Post your comment
Please wait...



Any advise would be helpful.
Thanks
I will suggest that you open your page in Firefox with the Firebug Add-On enabled. Open the "Net" tab and verify if the response from the server is correct.
Also, please read http://www.dhtmlgoodies.com/forum/viewtopic.php?f=30&t=568
Thanks alot. I love the work that has gone into this site.
Jc
It's difficult to say what's wrong without seeing your code.
An completely different alternative may be to use the Mootools library(mootools.net) only. Request.JSON was implemented there after the script on this site was created. JSON makes it very easy to create functionality like the one showed in the script here.
Here's an example:
HTML page:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<head>
</head>
<body>
<script type="text/javascript" src="js/external/mootools-core-1.3-full-compat.js"></script>
<form>
<table>
<tr><td>Firstname:</td><td><input type="text" id="firstname" name="firstname"></td></tr>
<tr><td>Lastname</td><td><input type="text" id="lastname" name="lastname"></td></tr>
<tr><td>Address:</td><td><textarea name="address" id="address"></textarea></td></tr>
</table>
</form>
<script type="text/javascript">
var jsonRequest = new Request.JSON(
{
url: 'response.php',
onSuccess : function(person, txt) {
$('firstname').set('value', person.firstname)
$('lastname').set('value', person.lastname)
$('address').set('value', person.address)
},
noCache : 1
}).get({'id': '1' });
</script>
</body>
</html>
This page sends a request to response.php and asks for the data for "id=1". The data returned from response.php may look like this:
{ "firstname" : "John","lastname" : "Doe","address" : "Somewhere" }
Basically I lookup data with a unique ID then its matched up with some other variables that are currently available into a table. Sadly after messing with it a while I can't get it to submit those fields since the form action is already used to look them up.
Any ideas on something I could try? I hate to bother you but this would be very useful in this little project and this lookup code works very well.
Thank you.
CB
Any ideas?
Thanx..
BT
I'm a programmer in Perl (CGI's / SSI's). I know little of javascript, and much less of AJAX.
Thrashing my scripts, JS scripts and apache logs, I realized that the arguments forwarded by AJAX are wrong:
In the ajax.js:
If this.method = "POST", results in: POST /myScript.cgi?id=1001
POST has no arguments in query
If this.method = "GET", results in: GET /myScript.cgi?id=1001?rndval=1303660905504
The argument "id" has value '1001?rndval=1303660905504'
So, I implemented a sort of url strip and set the method to GET, and told it to ajax.js.
The new JS code is as follows:
var ajaxObjects = new Array();
var currentClientID=false;
function getClientData() {
var indexThis = ajaxObjects.length;
ajaxObjects[indexThis] = new sack();
var clientID = document.getElementById("clientID").value.replace(/[^0-9a-z_]/g,"");
if(clientID==currentClientID){ return; }
currentClientID = clientID;
// I implemented a sort of url's strip and set the method to GET, and told it to ajax.js.
var url = "getClient.php?getClientId="+clientID; // full url to get
if(url.indexOf('?')>=0) {
ajaxObjects[indexThis].method="GET"; // defined method to GET
var string = url.substring(url.indexOf("?"));
url = url.replace(string,"");
string = string.replace("?","");
var items = string.split(/&/g);
for(var no=0;no<items.length;no++) {
var tokens = items[no].split("=");
if(tokens.length==2) { ajaxObjects[indexThis].setVar(tokens[0],tokens[1]); }
}
url = url.replace(string,"");
}
// end of implementations
ajaxObjects[indexThis].requestFile = url; // Specifying which file to get
ajaxObjects[indexThis].onCompletion = function(){ showClientData(indexThis); }; // Specify function that will be executed after file has been found
ajaxObjects[indexThis].runAJAX(); // Execute AJAX function
}
function showClientData(indexThis) {
var formObj = document.forms["clientForm"];
eval(ajaxObjects[indexThis].response);
}
function initFormEvents() {
document.getElementById("clientID").onblur = getClientData;
document.getElementById("clientID").focus();
}
window.onload = initFormEvents;
After changes in the JS script and without changing the ajax.js,
results in: GET /myScript.cgi?id=1001&rndval=1303660978053
cannot get focus
but it's working fine at firefox. any solution for this ?
I'm JSP coder. Could you please convert the getClient.php into jsp. I would try your goodies since my project required me to do this trick.
Thank
I got an js error at the
eval(ajax.response); (for original code) also
eval(ajaxObjects[indexThis].response); (andre version)
Any idea.
This error indicates that there's a problem with the data received from the server.
If you have firefox, please install the Firebug add on. When installed, activate it.
Open your ajax client lookup page and type something in the "id" field, i.e. the field triggering the lookup event.
Now, pay attention to the console page in Firebug. When you typed in the id, you should see a new line appearing in the console, something like :
[+] http://www.yourdomain.com/getClient.php?getClientId=1001
Click on the [+] button in front of the line and then on the "Response" tab. What do you see there ?
If it's working correctly, you should see something like :
formObj.firstname.value = 'John';
formObj.lastname.value = 'Doe';
formObj.address.value = 'Kings square 10';
formObj.zipCode.value = '4070';
formObj.city.value = 'RANDABERG';
formObj.country.value = 'NORWAY';
Hi,
I have tried your advice but still got same error. Below are my complete code.
var ajaxObjects = new Array();
var currentClientID = false;
function getClientData()
{
var indexThis = ajaxObjects.length;
ajaxObjects[indexThis] = new sack();
var clientId = document.getElementById('New_ICNo').value;
currentClientID = clientId
ajaxObjects[indexThis].requestFile = 'getClient.jsp?nic='+clientId;
ajaxObjects[indexThis].onCompletion = function(){ showClientData(indexThis); };
ajaxObjects[indexThis].runAJAX();
}
function showClientData(indexThis)
{
var formObj = document.forms['form1'];
eval(ajaxObjects[indexThis].response);
}
function initFormEvents()
{
document.getElementById('New_ICNo').onblur = getClientData;
document.getElementById('New_ICNo').focus();
}
window.onload = initFormEvents;
form name='form1' id='form1' method='post' action='client.jsp'
input name='New_ICNo' type='text' id='New_ICNo' size='16' maxlength='14'
input name='Old_ICNo' type='text' id='Old_ICNo' size='10' maxlength='10'
input name='L_Name' type='text' id='L_Name' size='80' maxlength='60'
getClient.jsp
String Recordset1__NewIC = "";
if (request.getParameter("nic") != "") {Recordset1__NewIC = request.getParameter("nic");}
Driver DriverRecordset1 = (Driver)Class.forName(MM_DISConn_DRIVER).newInstance();
Connection ConnRecordset1 = DriverManager.getConnection(MM_DISConn_STRING,MM_DISConn_USERNAME,MM_DISConn_PASSWORD);
PreparedStatement StatementRecordset1 = ConnRecordset1.prepareStatement("SELECT NewICNo, OldICNo, Defaulter_Name FROM defaulter.dis_defaulterparticular WHERE NewICNo = ?");
StatementRecordset1.setObject(1, Recordset1__NewIC);
ResultSet Recordset1 = StatementRecordset1.executeQuery();
boolean Recordset1_isEmpty = !Recordset1.next();
boolean Recordset1_hasData = !Recordset1_isEmpty;
Object Recordset1_data;
int Recordset1_numRows = 0;
String nic = Recordset1.getString(1);
String oic = Recordset1.getString(2);
String nam = Recordset1.getString(3);
out.print("formObj.Old_ICNo.value = '"+oic+"';"+"
");
out.print("formObj.L_Name.value = '"+nam+"';"+"
");
Firebug 1.7.1
(On Screen)
formObj.Old_ICNo.value = 'A10101010';
formObj.L_Name.value = 'THIS IS TEST DATA 1';
Firebug Console
html
head
/head
body
formObj.Old_ICNo.value = 'A10101010';
br
formObj.L_Name.value = 'THIS IS TEST DATA 1';
br
/body
/html
There seems to be a problem with the response from the server. Tags such as
<html> and <body> should not be there. All that should be sent from the server is this:
formObj.Old_ICNo.value = 'A10101010';
formObj.L_Name.value = 'THIS IS TEST DATA 1';
Thank for pointing me where the problem is. Found that the problem in my getClient.jsp page where I'm using out.print statement combine with html break line.
To share with others, the correct syntax are :
out.print("formObj.Old_ICNo.value = '"+oic+"';");
out.newLine();
out.print("formObj.L_Name.value = '"+nam+"';");
Thank you very much.
in my database i have two ways of data sometimes names are be wroten with accents and sometimes they are converted by the code htmlentities of PHP so then go to the data base with html codes like in the word "feet" in portuguese is "pé" in my database this save like "pé" when your code fills my HTML the code ignore the charset and write in the HTML "pé" no "pé" how the all of other codes i use they change the HTML codes normally but this java dont he ignores totally the conversion do you know how i can solve that.
i need help
the code i use cames down:
connect_cep.php
(i'm setting the char set here for the db retrieve results correctly)
cadastro.php
this code was in the place of
window.load = initformevents ();
this is the java he still in a output archive
java.js
// funcao consulta cep
var ajax = new sack();
var currentClientID=false;
function getClientData()
{
var clientId = document.getElementById('cep').value.replace(/[^0-9]/g,'');
if(clientId.length==8 && clientId!=currentClientID){
currentClientID = clientId
ajax.requestFile = 'cep.php?cep='+clientId; // Specifying which file to get
ajax.onCompletion = showClientData; // Specify function that will be executed after file has been found
ajax.runAJAX(); // Execute AJAX function
}
}
function showClientData()
{
var formObj = document.forms['clientForm'];
eval(ajax.response);
}
function initFormEvents()
{
document.getElementById('cep').onblur = getClientData;
document.getElementById('nome').focus();
}
i made some changes here for use for my purpose this code.
cep.php
connect_cep.php
$conexao_cep = mysql_connect ("x.x.x.x", "xxx", "xxx");
$db_cep = mysql_select_db ("cep", $conexao_cep);
mysql_query("SET NAMES 'utf8'");
mysql_query('SET character_set_connection=utf8');
mysql_query('SET character_set_client=utf8');
mysql_query('SET character_set_results=utf8');
(i'm setting the char set here for the db retrieve results correctly)
cep.php
include("connect_cep.php");
$cep = $_GET['cep'];
$end = "";
$bairro = "";
$cidade = "";
$uf = "";
$temp = str_split($cep);
$temp1 = $temp[0].$temp[1].$temp[2].$temp[3].$temp[4];
$check_uf = "select * from uf where Cep1 = ".$temp1;
$execut = mysql_query($check_uf);
$result = mysql_fetch_array($execut);
$uf = $result['UF'];
$temp2 = strtolower($uf);
$uf_result = $temp2;
$temp_cep = $temp1."-".$temp[5].$temp[6].$temp[7];
$sql = "select * from ".$uf_result." where cep='".$temp_cep."'";
$exe = mysql_query($sql);
$reg = mysql_fetch_array($exe);
$end = $reg['tp_logradouro']." ".$reg['logradouro'];
$bairro = $reg['bairro'];
$cidade = $reg['cidade'];
if($end == " " && $bairro == "" && $cidade == "") {
echo "formObj.end.value = 'Endereco nao encontrado.';\n";
echo "formObj.bairro.value = 'Bairro nao encontrado.';\n";
echo "formObj.cidade.value = 'Cidade nao encontrada.';\n";
echo "formObj.uf.value = '".$uf."';\n";
}
else {
echo "formObj.end.value = '".$end."';\n";
echo "formObj.bairro.value = '".$bairro."';\n";
echo "formObj.cidade.value = '".$cidade."';\n";
echo "formObj.uf.value = '".$uf."';\n";
}
this is the php code how i use to make the search in the database.
here is the jsp file...
getClient.jsp
don't forget to change the requestFile name in head section...... :)
If you need this code, you can send a mail to me...
Deepak Jain
djain29@gmail.com
Is it possible to amend the script so that the client ID does not have to use numerical client ID's
eg I would like to be able to use an ID such as
George01
Any help would be appreciated as I don't really know any Javascript.
Regards
if(clientId.length==4 && clientId!=currentClientID){
tq.
How to use your code to look up values in two tables from different database while not the same form. I tried to use two codes at the same time on the same page and only one works.
If you have an example that would be published.
thank you
------- index2.html------------
<HTML>
<HEAD>
<style type="text/css">
body{
background-repeat:no-repeat;
font-family: Trebuchet MS, Lucida Sans Unicode, Arial, sans-serif;
height:100%;
background-color: #FFF;
margin:0px;
padding:0px;
background-image:url('/images/heading3.gif');
background-repeat:no-repeat;
padding-top:85px;
}
fieldset{
width:500px;
margin-left:10px;
}
</style>
<!-- script type="text/javascript" src="jquery-1.5.1.min.js"></script -->
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
</HEAD>
<BODY>
<form name="clientForm" action="ajax-client_lookup.html" method="post">
<fieldset>
<legend>Client information</legend>
<table>
<tr>
<td><label for="clientID">Client ID:</label></td>
<td><input name="clientID" id="clientID" size="5" maxlength="4"></td>
</tr>
<tr>
<td><label for="firstname">First name:</label></td>
<td><input name="firstname" id="firstname" size="20" maxlength="255"></td>
</tr>
<tr>
<td><label for="lastname">Last name:</label></td>
<td><input name="lastname" id="lastname" size="20" maxlength="255"></td>
</tr>
<tr>
<td><label for="address">Address:</label></td>
<!-- td><input name="address" id="address" size="20" maxlength="255"></td -->
<td><textarea name="address" id="address" size="20" maxlength="255"></textarea></td>
</tr>
<tr>
<td><label for="zipCode">Zipcode:</label></td>
<td><input name="zipCode" id="zipCode" size="4" maxlength="5"></td>
</tr>
<tr>
<td><label for="city">City:</label></td>
<td><input name="city" id="city" size="20" maxlength="255"></td>
</tr>
<tr>
<td><label for="country">Country:</label></td>
<!-- td><input name="country" id="country" size="20" maxlength="255"></td -->
<td>
<SELECT name="country" id="country">
<option value="">--</option>
<option value="PHILIPPINES">Philippines</option>
<option value="NORWAY">Norway</option>
</SELECT>
</td>
</tr>
<tr>
<td><input type="submit" id="submit" value="submit"></td>
<td><input type="reset" id="reset" value="reset"></td>
</tr>
</table>
</fieldset>
<p>Same as index.html, in JQUERY Valid client IDs in this example are 1001 - 1007.</p>
</form>
<form name="blah" action="ajax-client_lookup.html" method="post">
<fieldset>
<legend>Another Form</legend>
<table>
<tr>
<td><label for="test">test:</label></td>
<td><input name="test" id="test" size="20" maxlength="255" value="should not be resetted when you hit reset 1"></td>
</tr>
<tr>
<td><input type="submit" id="submit" value="submit"></td>
<td><input type="reset" id="reset" value="reset"></td>
</tr>
</table>
</form>
</fieldset>
<div id="images"></div>
<script type="text/javascript">
$("#clientID").bind("change", function(e){
$.getJSON("getClient2.php?cID=" + $("#clientID").val(),
function(data){
$.each(data, function(i,item){
if (item.field == "firstname") {
$("#firstname").val(item.value);
} else if (item.field == "lastname") {
$("#lastname").val(item.value);
} else if (item.field == "address") {
$("#address").val(item.value);
} else if (item.field == "zipCode") {
$("#zipCode").val(item.value);
} else if (item.field == "city") {
$("#city").val(item.value);
} else if (item.field == "country") {
$("#country").val(item.value);
}
});
});
});
</script>
</BODY>
</HTML>
----------------- end html -----------------
------------ getClient2.php ------------------
<?php
$connection = mysql_connect("host","user","pass");
mysql_select_db("db",$connection);
$id=$_GET['cID'];
if (isset($id)) {
$result=mysql_query("SELECT * FROM ajax_client WHERE clientID='$id'") or die("error: ".mysql_error());
while($plist=mysql_fetch_assoc($result)) {
$json = array(array('field' => 'firstname',
'value' => $plist[firstname]),
array('field' => 'lastname',
'value' => $plist[lastname]),
array('field' => 'address',
'value' => $plist[address]),
array('field' => 'zipCode',
'value' => $plist[zipCode]),
array('field' => 'city',
'value' => $plist[city]),
array('field' => 'country',
'value' => $plist[country]) //last item should have no comma
);
}
}
print json_encode($json);
?>
----------- end php ------------------
Need a bit of help here. I am trying to pull an image path back via the ajax and then have that image appear on the page after the client look up is done. For reference, there is a field in the database that I have hooked this up too that has the path for the image. It's name is photopath.
So basically in my php script I have or had this:
echo "formObj.photopath.value = '".$inf["photopath"]."';\n";
That would give me a value of:
uploades/image_name.jpg
When I checked my json code by calling getClients.php?clientID=Foster,%20David
I could see the image in the json coding just fine. But what I was stuck on was on how to get that image to actually appear in the html code.
I have a spot for it with an 'id' tag set, and tried using <span id="photopath"></span> and tried using <div id="photopath"></div> and neither of those would render the picture like it should.
So I went back to modify the php code and tried adding in the image src tag, and still got no results.
What I am looking to do is simple really.
User fills in a name and clicks out or tabs out of that field, and the results are returned (which is all working just fine now) and also show a picture that we have for that user. I would imaging, just like the ability to change the info of who you're looking up, and the responding information changes, I would imagine the image could do the same thing - just need help to get the image to actually appear in it's desired spot
Thanks in advance for any help/suggestions.
how you solved it?
I have multiple input fields for product numbers. Every time a field is filled in, the price has to be collected from the database from that field. Then all the prices of the filled in fields have to be summed up and shown in a field/div when the user onfocus the input field.
Thanks in advance for any help/suggestions.
if ($ inf = pg_fetch_array ($ res))
{
How would one select here
/ / echo "formObj.zipCode.value = '". $ inf ["zipcode"]. "' \ n";
/ / echo "formObj.city.value = '". $ inf ["city"]. "' \ n";
/ / echo "formObj.country.value = '". $ inf ["country"]. "' \ n";
}