I use autocomplete to achieve a Google like search where the search suggestions are in a dropdown while i type what i'm searching for.
The Output of my code
HTML
<td width="155" bgcolor="#999999">Client Name</td>
<td width="218" bgcolor="#999999"><input type="text" name="clientname" id="clientname" class="forinput" /></td>
script
<script type="text/javascript">
$(document).ready(function() {
$( "#clientname" ).autocomplete(
{
source:"getautocomplete.php",
minLength:1
})
});
</script>
getautocomplete.php
..databaseconnection
$term = trim(strip_tags($_GET['term']));//retrieve the search term that autocomplete sends
$qstring = "SELECT clientname FROM client WHERE clientname LIKE '%".$term."%'";
$result = mysql_query($qstring);//query the database for entries containing the term
while ($row = mysql_fetch_array($result,MYSQL_ASSOC))//loop through the retrieved values
{
$row['clientname']=htmlentities(stripslashes($row['clientname']));
$row_set[] = $row;//build an array
}
echo json_encode($row_set);//format the array into json data
What i want to achieve
I check my database connection and its correct. Can anybody explain to me what I'm doing wrong? did i missed something?
I don't think the result you are sending back is valid according to what jQueryUI is expecting.
Now you are building an array of arrays and you should only send the values back (assuming that the label
and the value
are the same, the name of the client):
// $row['clientname']=htmlentities(stripslashes($row['clientname']));
$row_set[] = htmlentities(stripslashes($row['clientname'])); //build an array
Also note the comments about the deprecated mysql_*
functions and sql injection.