Saturday, November 11, 2017

Ajax Search Box in PHP, MySQL and JQuery.

In this tutorial we are going to build AJAX search box using PHP. Now a days every website has integrated this kind of search feature. This search box populate the results in real time from MySQL database based on entered text in search box.

This Search box of HTML is completely controlled by JQuery function. On key-up event of input field (e.g. Search Box), This JQuery function send the request to "controller.php" page via. AJAX technique. This request find the best match from MySQL database and display the result in "search.php" page.

Build Live Search Box Using PHP, MySQL and AJAX skptricks

Simple Ajax Search Example

First Create "Post" Database Table
  `POSTID` int(3) NOT NULL,
  `POSTTITLE` varchar(100) NOT NULL,
  `POSTDETAILS` varchar(10000) NOT NULL,
  `POSTLINK` varchar(100) NOT NULL

Once You have created above table, Then put the records in this table.

Consists of database configuration details to establish database connection.

define('DB_SERVER', 'localhost');
define('DB_DATABASE', 'skptricksdemo');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');


Controller work is to control the flow of execution. Here on Key-Up, JQuery script send request to "controller.php" page and it will process the request and return response to be displayed.

 $searchVal = trim($_POST["search-data"]);
 $dao = new DAO();
 echo $dao->searchData($searchVal);


This DAO class helps to establish the database connection and populate/fetch the records from MySQL database on AJAX call using JQuery.

class DAO{
public function dbConnect(){
$dbhost = DB_SERVER; // set the hostname
$dbname = DB_DATABASE ; // set the database name
$dbuser = DB_USERNAME ; // set the mysql username
$dbpass = DB_PASSWORD;  // set the mysql password
try {
$dbConnection = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass); 
$dbConnection->exec("set names utf8");
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbConnection;
catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
public function searchData($searchVal){
try {
$dbConnection = $this->dbConnect();
$stmt = $dbConnection->prepare("SELECT * FROM `post` WHERE `POSTTITLE` like :searchVal");
$val = "%$searchVal%"; 
$stmt->bindParam(':searchVal', $val , PDO::PARAM_STR);   
$Count = $stmt->rowCount(); 
//echo " Total Records Count : $Count .<br>" ;
$result ="" ;
if ($Count  > 0){
while($data=$stmt->fetch(PDO::FETCH_ASSOC)) {          
$result = $result .'<div class="search-result">'.$data['POSTTITLE'].'</div>';    
return $result ;
catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();

This page consists of Jquery, AJAX, PHP and HTML code, which helps to fetch records form MySQL database when user enter any text in search box.

  1. JQuery script helps to detect entered text in search box
  2. AJAX Code helps to fetch records from database and display the result in "search.php" page without page refresh.
    <script src="jquery-3.2.1.min.js">
        padding: 10px;
        border: solid 1px #BDC7D8;
        margin-bottom: 20px;
        display: inline;
        width: 100%;
        border-bottom:solid 1px #BDC7D8;
        font-family:Times New Roman;
        font-size: 20px;
      $(document).ready(function() {
        $('#search-data').unbind().keyup(function(e) {
          var value = $(this).val();
          if (value.length>3) {
          else {
      function searchData(val){
        $('#search-result-container').html('<div><img src="preloader.gif" width="50px;" height="50px"> <span style="font-size: 20px;">Please Wait...</span></div>');
          'search-data': val}
               , function(data){
          if(data != "")
            $('#search-result-container').html("<div class='search-result'>No Result Found...</div>");
              ).fail(function(xhr, ajaxOptions, thrownError) {
          //any errors?
          //alert with HTTP error
    <div style="width: 700px;margin:40px auto;">
      <div id="search-box-container" >
        <label > Jquery search box using Ajax : 
        <input  type="text" id="search-data" name="searchData" placeholder="Search By Post Title (word length should be greater than 3) ..." autocomplete="off" />
      <div id="search-result-container" style="border:solid 1px #BDC7D8;display:none; ">

If You want to perform click event in search result list, then you might need to follow below steps:

METHOD - 1 :
$('body').delegate(".search-result", "click", function(e){
    // write you logic.....


METHOD - 2 :
$(document).on('click', '.search-result', function() {
        // write you logic.....

Download Link :


  1. this is good my brodher ı use this in my side thanks

  2. Replies
    1. It is working perfectly. Refer the project available in Github repository :