I have a search box that gives you a list of suggested results based on data from a MySql database. If the user types A and the words Apple
and Animal
are in the databse, then the suggestion box will show both results. Currently, there is no way for me to click one of the results and have it fill the text box, and no matter what I try and do, I can't seem to get it to work. Currently, I'm working with something that looks like this:
echo '<script type ="text/javascript">';
echo 'function textFill(){';
echo ' var txt=document.getElementById("userInput").value= <li onclick ="textFill(this.value)">' .$matched[$count].'</li>'; //Suggestion results
echo '}';
echo"</script>";
}
I'll be honest, I'm not sure if this is even the right path to be going, but I found a few examples that were vaguely similar to this, so that's that direction I went with it. With this set up, the suggestion box doesn't even display, but if I take away the echo '<script type ='text/javascript>'
it will display the results plus the whole line of getElement
code. How would I go about getting this to work properly? I can show more code if necessary.
EDIT: I'm providing more code to show more of my PHP:
if(isset($_GET['userInput'])){
$value = $_GET['userInput']; //assign the value
strtolower($value);
}else{
echo "no input";
}
//Select query
$sql = "SELECT Device_type FROM Device WHERE Device_type LIKE '%".$value."%';";
if($result = mysqli_query($conn, $sql)){
if(mysqli_num_rows($result) > 0){
//Store the result in an array list[]
while($row = mysqli_fetch_array($result)){
$list[] = $row['Device_type'];
}
}else{
//set a null value to list[] if no result to prevent error
$list[] = "";
}
}
if(!empty($value)){
if($matched = preg_grep('~'.$value.'~i', $list)){
$count = 0;
echo '<ul>';
while($count < sizeOf($list)){
if(isset($matched[$count])){
echo '<li > ' .$matched[$count].'</li>';
}
$count++;
}
echo '</ul>';
echo json_encode($data);
}else{
echo "No result";
}
Assume you have following files served with your web server.
|- search.php
|- index.html
In your index.html file:
<!-- loading JQuery library -->
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<!-- code for capturing user input, sending it to server (search.php) and upon receiving suggestions populating them under the search box -->
<script>
$(document).ready(function() {
$('#searchbox').keyup(function() { // upon every key up when user is typing
$('#suggestions').html(''); // clear if any previous suggestions
var input = $(this).val();
$.getJSON( // sending a GET request via AJAX expecting a JSON response
'search.php', // to this URL where the PHP file is
{
searchQuery: input // with the text user typed in
},
function(data) { // upon receiving a response
$(data).each(function() { // iterate through the suggestions data received as JSON
var suggestion = '<option value=' + this + '>'; // create an <option> element with the each suggestion
$('#suggestions').append(suggestion); // and append it to the suggestions <datalist>
});
}
});
});
});
</script>
<!-- search form -->
<input id="searchbox" name="searchbox" type="search" list="suggestions">
<datalist id="suggestions">
<!-- suggestions will be populated here when user is typing -->
</datalist>
Your search.php file:
$term = $_GET['searchQuery'];
$suggestions = [];
if(isset($term) && !empty($term)){
$servername = "your_db_servername"; // Ex: localhost
$username = "your_db_username"; // Ex: root
$password = "your_db_password";
$dbname = "your_db_name";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if(!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT Device_type FROM Device WHERE Device_type LIKE '". $term ."%';";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result)) {
array_push($suggestions, $row["Device_type"]);
}
}
mysqli_close($conn);
echo json_encode($suggestions);
}
However you should note that sending AJAX request on evey keyup event can be quite overwhelming especially if the user is typing fast.
To make it more efficient it is a good idea to debounce the keyup event.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-throttle-debounce/1.1/jquery.ba-throttle-debounce.min.js "></script>
<script>
$(document).ready(function() {
$('#searchbox').keyup($.debounce( 250, function() { // act upon keyup events every 250 milliseconds when user is typing
$('#suggestions').html('');
var input = $(this).val();
$.getJSON(
'search.php',
{ searchQuery: input },
function(data) {
$(data).each(function() {
var suggestion = '<option value=' + this + '>';
$('#suggestions').append(suggestion);
});
}
);
}));
});
</script>