Il widget Autocomplete di jQuery UI ha un formato specifico per la risposta JSON.
jQuery UI richiede il seguente formato nella risposta JSON:
[{"value":"A","id":1},{"value":"B","id":2}]
Di seguito due soluzioni in PHP e Node.js.
PHP
header('Content-Type: application/json');
$term = $_GET['term'];
$output = array();
if(!empty($term)) {
$query = "SELECT name, id FROM data WHERE name LIKE '%" . $db->escape($term) . "%'";
$results = $db->fetch($query);
if($db->numRows > 0) {
foreach($results as $result) {
$output[] = array(
'value' => $result->name,
'id' => $result->id
);
}
}
}
echo json_encode($output);
exit();
Node.js
const express = require('express');
const bodyParser = require('body-parser');
const Data = require('./models/data');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/api/suggest', function(req, res) {
var term = req.body.term;
var output = [];
if(term && term.length > 0) {
var reg = new RegExp(term, 'i');
Data.find({name: reg}, function(err, results) {
if(!err && results.length > 0) {
results.forEach(function(result) {
var obj = {
value: result.name,
id: result.id
};
output.push(obj);
});
res.json(output);
} else {
res.json(err);
}
});
} else {
res.json(output);
}
});