jQuery のオートコンプリート ウィジェットを試していますが、壁にぶち当たりました。いくつかの入力/ガイダンスをいただければ幸いです。
基本的に、誰かが人の名前を入力するフォームがあります... jQuery はデータベースにクエリを実行し、一致するものを提案します。フォームには、JSON データから入力する必要がある 2 つのフィールド (name フィールドと非表示の ID フィールド) があります。これまでのところ、選択したときに提案を提供し、名前フィールドに入力するだけで取得できますが、非表示の ID フィールドを更新することはできませんでした。jQueryコードから何かキーが欠けている必要があることはわかっていますが、それを理解していません。「select」イベントを使用して値を設定しようとしましたが、うまくいきませんでした。
関連する FORM コードは次のとおりです。
<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>
関連するjQueryコードは次のとおりです。
$(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);
}
});
});
GetContactNames.php からの関連する 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);
GetContactNames.php の結果の出力は次のようになります。
([{"id":"1","name":"Santa Clause"},{"id":"2","name":"Joe Blow"}])
助言がありますか?