I am trying out jQuery's autocomplete widget and have kind of run into a wall. Would appreciate some input/guidance.
Essentially, I have a form where someone will type in the name of a person...jQuery will then query the database and suggest matches. The form has two fields that need to be filled from the JSON data - the name field and a hidden ID field. So far, I can get it to only give suggestions and fill in the name field when selected but have had no luck at getting it to update the hidden ID field. I know I have to be missing something key from the jQuery code, but haven't figured it out. I have tried setting values using the "select" event, but with no luck.
Here is the relevant FORM code:
<div id="formblock" class="stack">
<label>Project POC: <span class="error" name="proj_poc_error" id="proj_desc_error">This field is required.</span></label>
<input type="text" name="proj_poc" id="proj_poc">
<input type="hidden" name="proj_poc_id" id="proj_poc_id" value="NOT SET">
</div>
Here is the relevant jQuery code:
$(function() {
$( "#proj_poc" ).autocomplete({
source: function(request, response){
$.getJSON("/includes/AJAX/GetContactNames.php?callback=?", request, function(data){
var suggestions = [];
$.each(data, function(i, val){
suggestions.push(val.contacts);
});
response(suggestions);
});
},
minLength: 2,
select: function( event, ui ){
//Should display user ID a
alert(ui.item.id + ui.item.contacts);
}
});
});
Here is the relevant PHP from GetContactNames.php
//Initiate the session
session_start();
//Load custom classes
include_once ('../../ops.inc.php');
//Get the search term from GET
$param = $_GET['term'];
//Create new dblink class and connect to db
$uplink = new dblink();
$uplink->connect();
//Create new dbcontrol class
$control = new dbcontrol();
//Set the query to select ID and CONCAT'd NAME from Contact Table
$control->query = "SELECT `id`, CONCAT_WS(\" \",`firstname`,`lastname`) AS 'contacts' FROM `addressbook` WHERE `firstname` REGEXP '^$param'";
//Execute the query
$control->execute();
//Set an iterator value to 0
$i = 0;
//Get the results into array, then iterate.
while($row = $control->toAssocArray()){
foreach($row as $column=>$value){
$results[$i][$column] = $value;
}
$i++;
}
//Set the response string and encode for json
$response = $_GET['callback']."(".json_encode($results).")";
//Display the response string
echo $response;
//Disconnect from the database
$uplink->disconnect();
//Destroy classes
unset($uplink, $control);
The output of the GetContactNames.php results look like this:
([{"id":"1","name":"Santa Clause"},{"id":"2","name":"Joe Blow"}])
Any suggestions?