รายละเอียดของการตอบ ::
index.php
<!DOCTYPE html>
<html>
<head>
<title>Webslesson Tutorial | Autocomplete Textbox using Bootstrap Typehead with Ajax PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
</head>
<body>
<br /><br />
<div class="container" style="width:600px;">
<label>Search Country</label>
<input type="text" name="country" id="country" class="form-control input-lg" autocomplete="off" placeholder="Type Country Name" />
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#country').typeahead({
source: function(query, result)
{
$.ajax({
url:"fetch.php",
method:"POST",
data:{query:query},
dataType:"json",
success:function(data)
{
result($.map(data, function(item){
return item;
}));
}
})
}
});
});
</script>
fetch.php
<?php
//fetch.php
$connect = mysqli_connect("localhost","sa","sa", "hos");
mysqli_set_charset($connect, "utf8");
$request = mysqli_real_escape_string($connect, $_POST["query"]);
$query = "
SELECT subject FROM risk_report WHERE subject LIKE '%".$request."%'
";
$result = mysqli_query($connect, $query);
$data = array();
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$data[] = $row["subject"];
}
echo json_encode($data);
}
?>