javascript - how to connect jquery ui auto-complete widget with database?
190
upload.php
<?php
include('lib.php');
$text = $mysqli->real_escape_string($_GET['term']);
$query = "SELECT * FROM user WHERE area LIKE (:keyword) ORDER BY id ASC
LIMIT 0, 10";
$result = $mysqli->query($query);
$json = '[';
$first = true;
while($row = $result->fetch_assoc())
{
if (!$first) { $json .= ','; } else { $first = false; }
$json .= '{"value":"'.$row['area'].'"}';
}
$json .= ']';
echo $json;
?>
area_list.js
$(function(){
var test=["red","blue","pink","Black" ,"Grey"];
$("#term2").autocomplete({
source:'<?php include upload_where.php; ?>'
});
});
HTML
<input id="term2" placeholder="e.g New Delhi, Mumbai" />
If you think the code is right is it possible maybe my server doesn't support json because i haven't used json before.
Answer
Solution:
You can't include your php in javascript. So you need to create a php script for autocomplete. In this script, its better using an array to store your results then convert it to json using "json_encode".
autocomplete.php :
For the javascript, use ajax to retrieve your results
Answer
Solution:
You were using a string as input but you do need an array as autocomplete source.
If you don't want to code an ajax request, and if your js is generated on the fly by php, you can replace your code by this one:
However it's not a good idea to use php to generate your js. So you can use ThinkTank answer's