Reputation: 2226
I have a Bootstrap tyepahead that gets live data from my database. Rather than just returning one word from the database (the person's username), I want to be able to return multiple values (an image link and some other information from the database).
HTML and jQuery/Ajax:
<input class="typeahead" type="text" data-provide="typeahead" autocomplete="off" placeholder="Type something...">
<script>
$('.typeahead').typeahead({
source: function (query, process) {
$.ajax({
url: 'php/script.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + query,
success: function(data) {
process(data);
}
});
}
});
</script>
PHP:
<?php
include_once("connect_info.php");
$cxn = mysqli_connect($host, $user, $pass, $db) or die ("Couldn't connect to the server. Please try again.");
$return = array();
if(isset($_POST['query'])){
$stmt = $cxn->prepare('SELECT user_id FROM users WHERE username LIKE concat("%", ?, "%")');
$stmt->bind_param('s', $_POST['query']);
$stmt->execute();
while ($row = $result->fetch_assoc()) {
$return[] = $row['user_id'];
}
}
$json = json_encode($return);
print_r($json);
?>
How would this be done?
Upvotes: 0
Views: 4001
Reputation: 2226
Solved this myself, it was a lot easier than I thought it would be.
Here's my new code:
HTML and jQuery/Ajax:
<input class="typeahead" type="text" data-provide="typeahead" autocomplete="off" placeholder="Type something...">
<script>
$('.typeahead').typeahead({
source: function (query, process) {
$.ajax({
url: 'php/script.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + query,
success: function(data) {
process(data);
}
});
},
highlighter: function(data) {
var parts = data.split(','),
html = '<img src="pictures/' + parts[0] + '.jpg" />';
html += '<div class="info">' + parts[1] + '</div>';
return html;
},
});
</script>
PHP:
<?php
include_once("connect_info.php");
$cxn = mysqli_connect($host, $user, $pass, $db) or die ("Couldn't connect to the server. Please try again.");
$return = array();
if(isset($_POST['query'])){
$stmt = $cxn->prepare('SELECT user_id, username FROM users WHERE username LIKE concat("%", ?, "%")');
$stmt->bind_param('s', $_POST['query']);
$stmt->execute();
while ($row = $result->fetch_assoc()) {
$return[] = $row['user_id'] . ',' . $row['username'];
}
}
$json = json_encode($return);
print_r($json);
?>
Upvotes: 0
Reputation: 11
You can return array of Json objects. like [ {user_name:"XYZ", image_link:"http://www.mysite.com/my_image}.... ] I do it this way in python, I am sure you can do the same in PHP.
Please take a look at the last example [ best picture winner ] on the typeahead examples page. http://twitter.github.io/typeahead.js/examples/
Upvotes: 1