I'm having issues with getting bootstrap typeahead to return data as a json array from my MySQL database.
Here's what I have so far:
$('.typeahead').typeahead({
items: 5,
source: function (query, process) {
$.ajax({
url: 'typeahead.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + query,
success: function(data) {
process(data);
}
});
},
highlighter: function(data) {
// decode JSON data and return it here
},
updater: function(data) {
console.log("CLICKED!");
},
});
And here's the PHP file:
$search_for = $_POST['query'];
$return = array();
$stmt = $cxn->prepare('SELECT username, display_name FROM users WHERE username LIKE concat("%", ?, "%") OR display_name LIKE concat("%", ?, "%")');
$stmt->bind_param('ss', $search_for, $search_for);
$stmt->execute();
$result = $stmt->get_result();
while (($row = $result->fetch_assoc())) {
array_push($return, array($row['username'], $row['display_name']));
}
$json = json_encode($return);
echo $json;
And here's the JSON it returns:
[["username","Display Name"],["username2","Display Name 2"]]
However, this code doesn't work when I test out the typeahead. It gives the following error in console:
So, my question is, how do you properly get multiple pieces of data from a database and put it into a json array?