This tutorial shows how to create ajax search form using PHP, Jquery and Mysql. When you click the search button or press enter key the results will be displayed on the same page and without refresh page process. This is very interesting and simple. You may also like How to search in an array with preg_grep using php and Bootstrap search box
HTML and jQuery Code
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#find").keyup(function () {
fetch();
});
});
function fetch()
{
var val = document.getElementById("find").value;
$.ajax({
type: 'post',
url: 'fetch.php',
data: {
get_val: val
},
success: function (response) {
document.getElementById("search_items").innerHTML = response;
}
});
}
</script>
</head>
<body>
<div id="search_box">
<center>
<p>How to FullText Search System Using Ajax, Mysql and PHP</p>
<form method="get" action="">
<input type="text" name="get_val" id="find" placeholder="Enter Your Text Here">
<input type="submit" name="search" id="search" value="Search">
</form>
<div id="search_items">
</div>
</center>
</div>
</body>
</html>
PHP Code (fetch.php)
<?php
define('DB_SERVER', "localhost");
define('DB_USER', "root");
define('DB_PASS', "");
define('DB_DATABASE', "whatsappdwld_db");
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
if (isset($_REQUEST['get_val'])) {
$term = $_REQUEST['get_val'];
$find = mysqli_query($con,"SELECT * FROM language WHERE MATCH(name,description) AGAINST( '$term' )");
while ($row = mysqlI_fetch_assoc($find)) {
echo "<a href='fetch.php?findval=" . $row['name'] . "'>";
echo $row['name'] . "<br>";
echo $row['description'];
echo "</a>";
}
exit;
}
?>