The code below was for instant search, such as google search.
Note that I didn't include the connect to database function here. Coz I think the database username and password setting would be different to yours.So please create your own if you want to test it. The mysql is set with a table is called "objects", and it has one column named "name".
whenever I type in anything, another new search box pop up, where I was expecting the search result.
Could anyone help PLEASE! I stuck on this for almost a day and need it working by tomorrow.. Thanks in advance!!
<!-- display the search area -->
<html>
<!-- google API reference -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<!-- my own script for search function -->
<center>
<form method="POST">
<input type="text" name="search" style="width:400px " placeholder="Search box" onkeydown="searchq();">
<input type="submit" value=">>">
<div id="output">
</div>
</form>
</center>
</html>
<?php
$output="";
if(isset($_POST["searchVal"])){
//get the search
$search=$_POST["searchVal"];
//sort the search
$search=preg_replace("#[^0-9a-z]#i","",$search);
//query the search
$query=mysqli_query($conn,"SELECT * from objects WHERE name LIKE '%$search%'") or die("could not search!");
$count=mysqli_num_rows($query);
//sort the result
if($count==0){
$output="there was no search result";
}
else{
while($row=mysqli_fetch_assoc($query)){
$object_name=$row["name"];
$output.="<div>".$object_name."</div>";
}
}
}
?>
<!-- instant search function -->
<script type="text/javascript">
function searchq(){
// get the value
var searchTxt = $("input[name='search']").val();
// post the value
$.post("search.php",{searchVal: searchTxt},function(output){
$("#output").html(output);
});
}
</script>