i trying set jquery autocomplete uses results php mysql query.
i have basic autocomplete working 1-d array of values, can't work 2-d array. want use 2-d array 1 column populates auto-complete , 1 column populates value submitted in form (either through value of input or hidden value).
i know format needs after using json_encode()
: [ { label: "choice1", value: "value1" }, ... ]
can't quite that...
the code below not working code represents do: display names in autocomplete field, submit page_id.
here code:
$query = "select name, page_id table city = '{$location}' order name"; $result = $mysqli->query($query); while($row = mysqli_fetch_assoc($result)){ $array[] = $row; } <script> $( function() { var array = <?php echo json_encode($array); ?>; $( "#input" ).autocomplete({ source: array }); } ); </script>
when want distinguish value , label, must provide array of objects, described in jquery autocomplete documentation:
source
array: array can used local data. there 2 supported formats:
- an array of strings:
[ "choice1", "choice2" ]
- an array of objects label , value properties:
[ { label: "choice1", value: "value1" }, ... ]
as looking second option should in php prepare exact structure. can follows:
while($row = mysqli_fetch_assoc($result)){ $array[] = array( "label" => $row['name'], "value" => $row['page_id'] ); }
this adds so-called associative arrays normal (indexed) array. json_encode
translates associative arrays object notation.
Comments
Post a Comment