What is search autocomplete?
Autocomplete is also known as typeahead. As users begin typing their queries, the script shows relevant options.
Autocomplete is also known as typeahead. As users begin typing their queries, the script shows relevant options.
<div class="container">
<form>
<div class="input-group">
<input name="songs" id="songs" type="text" class="form-control form-control-no-focus" autocomplete="off" placeholder="Search song title ">
<div class="input-group-append">
<button class="btn btn-secondary btn-no-focus demo-button-search" type="button">
<i class="fa fa-search"></i>
</button>
</div>
</div>
</form>
</div>
<link href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css" rel="stylesheet" type="text/css">
<script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js"></script>
<script>
$(function() {
$('#songs').typeahead({
hint: true,
highlight: true,
minLength: 2,
maxLength: 10,
maxItem: 10,
source: function(query, result) {
$.ajax({
url: "data.php",
method: "POST",
data: {
query: query
},
dataType: "json",
success: function(data) {
result($.map(data, function(item) {
return item;
}));
}
})
}
});
});
</script>
<?php
$conn = new mysqli ("server", "user", "password", "database");
mysqli_set_charset ($conn, "utf8");
if ($conn -> connect_error) {
die ("Error: " . $conn->connect_error);
}
$data = array();
$sql = "SELECT song, artist FROM top_100_songs
WHERE song LIKE '%".$request."%' OR artist LIKE '%".$request."%'
AND list_eu > 21.000 LIMIT 0, 40";
$result = $conn -> query($sql);
while ($row = $result -> fetch_assoc()) {
$data[] = $row["song"].' - '.$row["artist"];
}
echo json_encode($data);
$conn -> close();
?>