i have a table with the following structure

CREATE TABLE IF NOT EXISTS `test_check` (
  `id` int(4) NOT NULL AUTO_INCREMENT,
  `name` varchar(65) NOT NULL DEFAULT '',
  `lastname` varchar(65) NOT NULL DEFAULT '',
  `email` varchar(65) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;

i have a html page that has three text boxes, one for entering a search string and the other one for displaying the first name and surname of the returned row
the html page is as follows

<html>
<body>
<style>
#displayDiv{
background-color: #ffeeaa;
width: 200;
}
</style>
<script type="text/javascript">
function ajaxFunction(str)
{
var httpxml;
try
{
// Firefox, Opera 8.0+, Safari
httpxml=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
httpxml=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
httpxml=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}

function stateChanged()
{
if(httpxml.readyState==4)
{
document.getElementById("displayDiv1").value=httpxml.responseText;
document.getElementById("displayDiv2").value=httpxml.responseText;
}
}
var url="ajax-search-demock.php";
url=url+"?txt="+str;
url=url+"&sid="+Math.random();
httpxml.onreadystatechange=stateChanged;
httpxml.open("GET",url,true);
httpxml.send(null);
}
</script>
</head>
<body>
<form name="my">
Search: <input type="text"
onkeyup="ajaxFunction(this.value);" name="" />
<p>

Name: <input type="text" name="displayDiv" id="displayDiv1"><br>
Surname: <input type="text" name="displayDiv" id="displayDiv2">
<p>

<input name="" type="reset" value="Reset">

</form>

</body>
</html> 

the php code for searching the table is as follows

<?php
//***************************************
// This is downloaded from www.plus2net.com //
/// You can distribute this code with the link to www.plus2net.com ///
// Please don't remove the link to www.plus2net.com ///
// This is for your learning only not for commercial use. ///////
//The author is not responsible for any type of loss or problem or damage on using this script.//
/// You can use it at your own risk. /////
//*****************************************
//error_reporting(E_ERROR | E_PARSE | E_CORE_ERROR);
////// Your Database Details here /////////
$dbservertype='mysql';
$servername='127.0.0.1';
$dbusername='root';
$dbpassword='';
$dbname='delete_checkbox';

////////////////////////////////////////
////// DONOT EDIT BELOW /////////
///////////////////////////////////////

connecttodb($servername,$dbname,$dbusername,$dbpassword);
function connecttodb($servername,$dbname,$dbuser,$dbpassword)
{
global $link;
$link=mysql_connect ("$servername","$dbuser","$dbpassword");
if(!$link){die("Could not connect to MySQL");}
mysql_select_db("$dbname",$link) or die ("could not open db".mysql_error());
}
///////////////////// Main Code sarts ////////


$in=$_GET['txt'];
$msg="";
if(strlen($in)>0 and strlen($in) <20 ){
$t=mysql_query("select * from test_check where name like '$in%' OR lastname like '$in%' LIMIT 1");
while($nt=mysql_fetch_array($t)){ error_reporting(0);
$msg.=$nt[name];




}
}
echo $msg;

?>

The search results should display both the first name and last name but it's only displaying the first name in both textboxes. I need to display name in first textbox and surname in second textbox. Where am i getting it wrong?

Recommended Answers

All 10 Replies

You are returning only the name in a message not alsoo the lastname. Add lastname also and separate the name and lastname so you can distinguish them when returned from ajax cal, maybe with comma:

    ...
    while($nt=mysql_fetch_array($t)) { error_reporting(0);
        $msg.= $nt[name] . ',' . $nt[lastname];
    }
}
echo $msg;

On html page insert the name and lastname:

// split the returned string into array of name and lastname
nameAndLastnameArray = value=httpxml.responseText.split(',');

// insert name into appropriate box
document.getElementById("displayDiv1").value=nameAndLastnameArray[0];

// insert lastame into appropriate box
document.getElementById("displayDiv2").value=nameAndLastnameArray[1];

Thanks. It's now displaying the correct data in the correct fields. But there's an issue with the surname field displaying 'undefined' when you start removing text from the search box. Only the name field is going blank when you do that, and i want both fields to go blank. Why is that?

I guess because the nameAndLastnameArray[1] does not exist (is undefined) when removing. Can you describe what is the purpose of the page and the form.

You could use lenght property to check for the second element:

if(nameAndLastnameArray.length > 1) {
    // insert name into appropriate box
    document.getElementById("displayDiv1").value=nameAndLastnameArray[0];
    // insert lastame into appropriate box
    document.getElementById("displayDiv2").value=nameAndLastnameArray[1];
} else {
    // insert empty string into boxes
    document.getElementById("displayDiv1").value='';
    document.getElementById("displayDiv2").value='';
}

But I do not know whether this is the way you want to do it.

Well, i'm developing a web-based client underwriting system which will contain a lot of records. So at the moment i am trying to make it easier for the user to fill in forms so that they don't have to manually type in the fields, hence the reason for the search box which will automatically populate the other textboxes as the user types. So your help would be much appreciated.

A little modification in boj1 post.
As there may be a case when user has given only first name .

if(nameAndLastnameArray.length > 1) {
    // insert name into appropriate box
    document.getElementById("displayDiv1").value=nameAndLastnameArray[0];
    // insert lastame into appropriate box
    document.getElementById("displayDiv2").value=nameAndLastnameArray[1];
}  elseif(nameAndLastnameArray.length == 1) {
    // insert empty string into boxes
    document.getElementById("displayDiv1").value=nameAndLastnameArray[0];
    document.getElementById("displayDiv2").value='';
}
else {
    // insert empty string into boxes
    document.getElementById("displayDiv1").value='';
    document.getElementById("displayDiv2").value='';
}
commented: Good point +8

Wow. It's now working the way i want. Thanks a lot man. I wish i could shake your hand :)

So at the moment i am trying to make it easier for the user to fill in forms so that they don't have to manually type in the fields

Now you have an input box where only one name/surname can be displayed. But in cases like yours I think the practice is to display a list of matches which gets shorter the more characters you type in. So the principle is:

  • on keyup event you shoot the ayax and read the matches for whatever is currently typed in an input box
  • ajax returns an unordered list (<ul></ul>) of matches into a designated div
  • you use CSS to position the list directly under the textbox and shape it appropriately
  • usually the ajax does not get fired on first letter but once you have say three letters or more

I hope I guessed right what is your intention, please correct me if I am wrong.

Ok. U've just given me a great idea. So wat exactly would the code be like if i may ask?

Have a look at this article:

http://www.daniweb.com/web-development/javascript-dhtml-ajax/threads/447144/autoseggestion-styling

You will find a concept there. It is a bunch of texts to read but it is good if you get an idea how it goes. Then try to code it and when you have troubles come back here. Maybe it would be a good idea to start a new thread since this one has been marked as solved. If you start a new thread please PM me, otherwise I might not notice it.

Also have a look at these links for jquery plugins that do this functionality:

http://www.devbridge.com/projects/autocomplete/jquery/
http://www.daniweb.com/web-development/javascript-dhtml-ajax/threads/447144/autoseggestion-styling

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.