javascript - how to connect jquery ui auto-complete widget with database? -
upload.php
<?php include('lib.php'); $text = $mysqli->real_escape_string($_get['term']); $query = "select * user area (:keyword) order 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 think code right possible maybe server doesn't support json because haven't used json before.
you can't include php in javascript. need create php script autocomplete. in script, better using array store results convert json using "json_encode".
autocomplete.php :
<?php include('lib.php'); if(true === isset($_get['term']) && false === empty($_get['term'])) { $text = $mysqli->real_escape_string($_get['term']); $query = "select * user area (:keyword) order id asc limit 0, 10"; $result = $mysqli->query($query); $json = array(); $first = true; while($row = $result->fetch_assoc()) { $json[] = $row['area']; } header('content-type: application/json'); echo json_encode($json); } ?>
for javascript, use ajax retrieve results
$('#term2').autocomplete({ minchars:2, nocache: false, //default false, set true disable caching // callback functions: source: function( request, response ) { $.ajax({ url: "autocomplete.php", //correspond php page datatype: "json", data: {term: request.term}, success: function(data) { return data; } }); } });
Comments
Post a Comment