Ajax live search using jQuery Ajax and PHP

  •  
  •  
  •  
  •  
  •  
  •  

Ajax live search is a search form where you get search results instantly while you type. Therefore it makes  very easier for the users to find what they are looking for. In this tutorial I will demonstrate you Ajax live search using jQueyr Ajax and PHP.

Ajax live search using jQuery Ajax and PHP

Ajax live search – The HTML page

<div class="searchDiv">
  <label>Keywords : </label><input type="text" name="search" id="search" value="" placeholder="keywords (comma seperated)" autocomplete="off" />
  <div class="resultDiv"></div><!-- end of .resultDiv -->
  <div class="clearfix"></div>
</div><!-- end of .searchDiv -->

The above html code contains a input field where users can input keywords. Keywords should comma (“,”) separated. The instant results will be display within “resultDiv” div.

Ajax live search – The jQuery Ajax code

$(document).ready(function() {
  $("#search").keyup(function() {
    var keywords = $(this).val();
    if(keywords != "") {
      $.ajax({
        url: "get_search_result.php",
        data: {keywords : keywords},
        type: "POST",
        success: function(resp) {
          if(resp != "") {
            $(".resultDiv").html(resp).show();	
          } else {
            $(".resultDiv").html("").hide();
          }
        }
      });
    } else {
      $(".resultDiv").html("").hide();
    }
  });
  
  
  $(document).click(function() {
    $("#search").val("");
    $(".resultDiv").html("").hide();				   
  });
});

Create a”jquery_ajax.js” file within the “js” folder and put the above content in it. Each and every time user type a character, $(“#search”).keyup(function() {….}) function will execute. $.ajax({…}) function send a ajax request to the get_search_result.php page with the keywords parameter. If anything returns it will display within the resultDiv div.

Ajax live search – Fetch search result from database using PHP

<?php
if(isset($_POST['keywords'])) {
  $keywords_arr = explode(",", mysqli_real_escape_string($con, $_POST['keywords']));
  $like = "";
  foreach($keywords_arr as $key) {
    $key = trim($key);
    if($key != "") $like .= " `post_title` like '%".$key."%' or";
  }
  $like = substr($like, 0, -3);
  
  $sql = "select distinct * from `live_search` where ".$like." limit 20";
  $res = mysqli_query($con, $sql);
  echo "<ul>";
  if(mysqli_num_rows($res) > 0) {
    
    while($row = mysqli_fetch_object($res)) {
      if(file_exists("images/post_images/".$row->id.".jpg")) $img = "images/post_images/".$row->id.".jpg";
      else $img = "images/post_images/default.jpg";
      echo "<li><a href=''><img src='".$img."' width='50' height='50' />".$row->post_title."</a></li>";
    }
    
  } else {
    echo "<li>No match found!</li>";
  }
  echo "</ul>";
  echo "<div class='clearfix'></div>";
}
?>

Create a php file within the root folder. Name it get_search_result.php and write the above contents within it. The code performs a query which returns the matching result based on the keywords.

<?php
if(isset($_POST['keywords'])) {
  $keywords_arr = explode(",", mysqli_real_escape_string($con, $_POST['keywords']));
  $like = "";
  foreach($keywords_arr as $key) {
    $key = trim($key);
    if($key != "") $like .= " `post_title` like '%".$key."%' or";
  }
  $like = substr($like, 0, -3);
  ........................................................
  ........................................................
}
?>

First we explode the keywords where we found comma (“,”) and stored it in a array variable. The foreach($keywords_arr as $key) {….}  loop creates the conditional part of the MySql query. We get an extra  ” or” at the end of foreach loop. So, we subtract the last three character ” or” from the “$like” variable.

Ajax live search – The CSS code

.clearfix { clear:both; }
span { clear:both; display:block; margin-bottom:30px; }
span a { font-weight:bold; color:#0099FF; }
label { margin-top:20px; margin-bottom:3px; font-weight:bold;}
#search { padding:2px 5px; width:300px; float:right; }
.searchDiv {
  width:405px;
}
.resultDiv {
  display:none;
  float:right;
  width:302px; 
  max-height:200px;
  overflow:auto;
  border:1px solid #0099FF;
  padding:5px;
  z-index:999;
  background-color:beige;
}
ul {
  margin:0;
  padding:0;
}
ul li {
  list-style:none;
  clear:both;
  width:100%;
  padding:5px 0;
  border-bottom:1px solid #ccc;
}
ul li:hover, ul li:hover > a {
  background-color:#0099FF;
  color:#fff;
  cursor:pointer;
}

ul img {
  float:left;
  margin:0 5px;
  padding:3px;
  border:1px solid #ccc;
  border-radius:5px;
}
ul a {
  text-decoration:none;
  color:#666;
  display:inline-table;
}

Download the full article for better understanding. If you enjoy this article and think it is useful then please share this article with others.

About Mitrajit

One thought on “Ajax live search using jQuery Ajax and PHP

Leave a Reply

Your email address will not be published. Required fields are marked *

Prove you are a human *