I’m a currently a student and I studying/trying to make an autocomplete that gets the value and the ID based from the the query returned by the sql query. What I would like to happen is to store the ID of the returned row in a hidden field so that when the form is submitted I can determine the what is the ID of that particular row. I was already able to make the autocomplete textbox work. Sir/Ma’am your answers would be of great help and very much appreciated.
Here is my code for search.php:
<?php
$host = "localhost";
$user = "root";
$password = "";
$db = "isproj2";
// open connection
$connection = mysql_connect($host, $user, $password) or die ("Unable to connect!");
// select database
mysql_select_db($db) or die ("Unable to select database!");
$text = mysql_real_escape_string($_GET['term']);
$query = "Select SupplierName, SupplierID from tbl_supplier where SupplierName LIKE '%$text%'";
$result = mysql_query($query);
$json = '[';
$first = true;
while($row = mysql_fetch_array($result))
{
if (!$first) { $json .= ','; } else { $first = false; }
$json .= '{"value":"'.$row['SupplierName'].'"}';
}
$json .= ']';
echo $json;
?>
Here is the code for my script:
<script type="text/javascript">
$(document).ready(function()
{
$('#auto').autocomplete(
{
source: "search.php"
//minLength: 3
});
});
});
</script>
At first, I would say that you don’t need to build your JSON string by yourself. PHP include functions dedicated to theses tasks such as json_encode.
Now, if you want to store the value in a hidden field, you first have to give it to the autocomplete using JSON which should be formatted like this:
The
labelwill be automatically used by jQuery to fill theautocomplete.Then you have to use the
selectevent to bind the selected id into your hidden field. It could go like this:The
ui.itemobject represents the selected object.