I' m completely new to javascript, php etc ... and I really need some help to finish my traineeship application.
Here is my problem.
I' m using autocomplete on a database to find a specific company.
Autocompletion returns me Label and Value with the name of the company, but i need its ID because the rest of my application uses ID.
Here is an example :
This is what i got in POST :
array (size=23)
'company' => string 'example' (length=10)
So i still need the name of company but instead of "example" i want to have the ID of "example".
here is my search.php :
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'bsup';
if(!isset($company)) $company = '';
if(!isset($_POST['company'])) $_POST['company'] = '';
$db = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
$searchTerm = $_GET['term'];
$query = $db->query("SELECT * FROM tcompany where name like '%".$searchTerm."%' ORDER BY name ASC");
while ($row = $query->fetch_assoc()) {
$data[] = $row['name'];
}
//return json data
echo json_encode($data);
My HTML :
$(function() {
var cache = {};
$.ajaxSetup( { type: "post" } );
$( "#company" ).autocomplete({
minLength: 2,
select: function( event, ui ) {
$(event.target).val(ui.item.value);
$("#myform").submit();
},
source: function( request, response ) {
$.getJSON( "search.php", request, function( data, status, xhr ) {
response( data );
});
}
});
});
Thanks a lot for your help !
Update your json to include all the data you need. For example return an array like:
$data[$row['ID']] = $row['name']
If you need more data you can do an array of arrays like
$data[$row['ID']] = array($row['name'], $row['whatever'])
If you want to suggest the ID in your autocomplete instead of the name use:
$data[] = $row['ID']