top_menu

Monday, 27 May 2013

How to create a facebook type search suggestions script

.

This is an update to the old tutorial on "Facebook type search box with auto complete using jquery, ajax and PHP". This post explains, how to implement the search auto suggestion functionality similar to facebook, google.

It uses the power of jQuery, JSON, PHP, AJAX with CSS. Very easy to implement as well as modify the script according to perticular requirement.
 
Live Demo Download Script


Implementation steps are very simple

Create the required database tables

This database table stores the user information to search for. Import the sql.sql file into database OR execute the following sql into your database
CREATE TABLE IF NOT EXISTS `fsearch` (
  `uid` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(30) DEFAULT NULL,
  `email` varchar(100) DEFAULT NULL,
  `media` varchar(200) NOT NULL,
  `country` varchar(200) NOT NULL,
  PRIMARY KEY (`uid`),
  KEY `uid` (`uid`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;

INSERT INTO `fsearch` (`uid`, `username`, `email`, `media`, `country`) VALUES
(1, 'angularcode', 'info@angularcode.com', 'angularcode.jpg', 'India'),
(2, '2lessons', 'info@2lessons.info', '2lessons.jpg', 'India'),
(3, 'Swadesh', 'swadesh@gmail.com', 'swadesh.jpg', 'India'),
(4, 'Ipsita Sahoo', 'ipsita@gmail.com', 'ipsita.jpg', 'India'),
(5, 'Tamanna Priyadarsini', 'tamanna@gmail.com', 'tamanna.jpg', 'India'),
(6, 'Tapaswini Sahoo', 'tapaswini@gmail.com', 'linky.jpg', 'India'),
(7, 'Sandhya Samant', 'sandhya@gmail.com', 'sandhya.jpg', 'India'),
(8, 'Satvik Mohanty', 'satvik@gmail.com', 'satvik.jpg', 'India'); 

Configure includes/db.php

Configure the db.php file according to your database credentials
<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'YOUR_DB_USERNAME');
define('DB_PASSWORD', 'YOUR_DB_PASSWORD');
define('DB_DATABASE', 'YOUR_DB_NAME');
$connection = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD) or die(mysql_error());
$database = mysql_select_db(DB_DATABASE) or die(mysql_error());
?>

Add jQuery and fSearch scripts to your page (index.html)

<!--  
 fSearch 1.0 - jQuery plugin for facebook type search suggestions
 http://www.angularcode.com/
 Copyright (c) 2013 Ipsita Sahoo 
-->
<html>
<head>
<title>Facebook type search suggestions using jQuery, PHP and JSON</title>
<link rel="stylesheet" href="css/style.css">
<script type="text/javascript" src="js/jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="js/fsearch.js"></script>
</head>
<body>
<div class="container">
<h1>fSearch - Facebook type search suggestions using jQuery and PHP</h1>
<p>Start typing in the search box bellow</p>

<input id="searchInput" placeholder="Search for people, places and things"/>

</div>
</body>
<script>
$(document).ready(function()
{
  $('#searchInput').fsearch();
});
</script>
</html>

The js/fSearch.js file

(function($){
$.fn.fsearch = function(){
  var $searchInput = $(this);
  $searchInput.after('<div id="divResult"></div>');
  $resultDiv = $('#divResult');
  $searchInput.focus();
  $searchInput.addClass('searchi');
  $resultDiv.html("<ul></ul><div id='search-footer' class='searchf'></div>");
  $searchInput.keyup(function(e) {
  var q=$(this).val();
    if(q != '')
    { 
      var current_index = $('.selected').index(),
      $options = $resultDiv.find('.option'),
      items_total = $options.length;

      // When Down Arrow key is pressed
      if (e.keyCode == 40) {
          if (current_index + 1 < items_total) {
              current_index++;
              change_selection($options,current_index);
          }
      } 

      // When Up Arrow is pressed
      else if (e.keyCode == 38) {
          if (current_index > 0) {
              current_index--;
              change_selection($options,current_index);
          }
      }

      // When enter key is pressed
      else if(e.keyCode == 13){
        var id = $resultDiv.find('ul li.selected').attr('id');
        var name = $resultDiv.find('ul li.selected').find('.name').text();
        $searchInput.val(name); 
        $resultDiv.fadeOut();// Here you get the id and name of the element selected. You can change this to redirect to any page too. Just like facebook.   
      }
      else{
      $resultDiv.fadeIn();
      $resultDiv.find('#search-footer').html("<img src='img/loader.gif' alt='Collecting Data...'/>");
      
      // Query search details from database
      $.getJSON("json.php",{searchword: q},function(jsonResult)
      { 
        var str='';
        for(var i=0; i<jsonResult.length;i++)
          {
            str += '<li id=' + jsonResult[i].uid + ' class="option"><img class="profile_image" src="photos/'+jsonResult[i].media+'" alt="'+jsonResult[i].username+'"/><span class="name">' + jsonResult[i].username + '</span><br/>'+jsonResult[i].country+'</li>';
          }
          $resultDiv.find('ul').empty().prepend(str);
          $resultDiv.find('div#search-footer').text(jsonResult.length + " results found...");
          $resultDiv.find('ul li').first().addClass('selected');
      }); 

        $resultDiv.find('ul li').live('mouseover',function(e){
        current_index = $resultDiv.find('ul li').index(this);
        $options = $resultDiv.find('.option');
        change_selection($options,current_index);
      });

      // Change selected element style by adding a css class
      function change_selection($options,current_index){
        $options.removeClass('selected');
        $options.eq(current_index).addClass('selected');
        }
      }
    }
    else{
      //Hide the results if there is no search input
      $resultDiv.hide();
    }
  });    

  // Hide the search result when clicked outside
  jQuery(document).live("click", function(e) { 
    var $clicked = $(e.target);
    if ($clicked.hasClass("searchi") || $clicked.hasClass("searchf")){
    }
    else{
      $resultDiv.fadeOut(); 
    }
  });

  // Show previous search results when the search box is clicked
  $searchInput.click(function(){
    var q=$(this).val();
    if(q != '')
    { 
      $resultDiv.fadeIn();
    }
  });

  // Select the element when it is clicked
  $resultDiv.find('li').live("click",function(e){ 
    var id = $(this).attr('id');
    var name = ($(this).find('.name').text());
    $searchInput.val(name);
  });

  };
})(jQuery);

JSON.php file to collect data from database

<?php 
/**
* fSearch 1.0 - jQuery plugin for facebook type search suggestions
* http://www.angularcode.com/
* Copyright (c) 2013 Ipsita Sahoo 
*/
if($_GET)
{
$q=$_GET['searchword'];
$items = array();
include('includes/db.php'); // Includes database connection settings.
$sql_res=mysql_query("select uid,username,email,media,country from test_auto_complete where username like '%$q%' or email like '%$q%' or country like '%$q%' order by uid LIMIT 5");
while($row=mysql_fetch_array($sql_res))
{
$uid = $row['uid'];
$username=$row['username'];
$email=$row['email'];
$media=$row['media'];
$country=$row['country'];
$b_username='<b>'.$q.'</b>';
$b_email='<b>'.$q.'</b>';
$b_country='<b>'.$q.'</b>';
$final_username = str_ireplace($q, $b_username, $username);
$final_email = str_ireplace($q, $b_email, $email);
$final_country = str_ireplace($q, $b_country, $country);
$items[] = array('uid' => $uid, 'username' => $final_username, 'email' => $final_email, 'country' => $final_country, 'media' => $media);
}
header('Content-Type:text/json');
echo json_encode($items);
}
else{
 echo json_encode('No search string found');
}
?>

The CSS (used for styling) - css/style.css

*{ 
font-family:"trebuchet MS",verdana ;
font-size: 16px;
}
ul{ 
list-style::none;margin:0pt;padding:0pt;
}
h1{
margin-bottom: 0;
font-size: 1.17em;
}
p{
margin-top: 0;
}
.container{
width:700px;
margin:100px auto;
}
#searchInput
{
width:350px;
border:solid 1px #dedede;
padding:3px;
border-top-right-radius: 6px;
border-top-left-radius: 6px;
-moz-border-top-right-radius: 6px;
-moz-border-top-left-radius: 6px;
box-shadow: 0px 0px 5px #999;
border-width: 1px 1px 0px;
border-style: solid;
border-color: #efefef #DEDEDE #DEDEDE;
background-color: white;
}
#divResult
{
position:absolute;
width:348px;
display:none;
margin-top:-1px;
border:solid 1px #dedede;
border-top:0px;
overflow:hidden;
border-bottom-right-radius: 6px;
border-bottom-left-radius: 6px;
-moz-border-bottom-right-radius: 6px;
-moz-border-bottom-left-radius: 6px;
box-shadow: 0px 0px 5px #999;
border-width: 0px 1px 1px;
border-style: solid;
border-color: #eeeeee #DEDEDE #DEDEDE;
background-color: white;
}
#divResult ul li{
padding:4px; border-top:solid 1px #dedede; 
height:50px;
}
#divResult ul li:hover{
cursor: pointer;
}
#divResult ul li.selected{
background:#1BA1E2;
color:#FFFFFF;
cursor:pointer;
}
#divResult div#search-footer{
height: 15px;
text-align: center;
padding: 5px 0 10px 0;
background-color:#e2e2e2; 
}
#divResult ul li img.profile_image{
width:50px; height:50px; float:left; margin-right:6px;
}

Features 

  • Its a jQuery plugin. Hence it is very easy to integrate into any website or blog.
  • Works gracefully with any modern browser.
  • The keyboard navigation feature makes it handy to use.
  • The search results also includes a space to show up profile image.