top_menu

Sunday, 23 September 2012

Facebook type search box with auto complete using jquery, ajax and PHP

.

New version of facebook type search box released on request 


Facebook's search bar allows users to search for all users, communities, groups, apps and pages. It provides suggestions while typing. In this tutorial i'll explain you, how to create such a search input box in your website using jquery, ajax and php. I made the code short and simple to understand. Please suggest if any additional feature required.

facebook like autocomplete search box


Download ASP.NET Version
Configuring db.php
<?php
define('DB_SERVER', 'YOUR_DATABASE_SERVER');
define('DB_USERNAME', 'YOUR_DATABASE_USERNAME');
define('DB_PASSWORD', 'YOUR_DATABASE_PASSWORD');
define('DB_DATABASE', 'YOUR_DATABASE_NAME');
$connection = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD) or die(mysql_error());
$database = mysql_select_db(DB_DATABASE) or die(mysql_error());
?>
Creating the required tables in database
CREATE TABLE IF NOT EXISTS `test_auto_complete` (
  `uid` int(11) NOT NULL DEFAULT '0',
  `username` varchar(30) DEFAULT NULL,
  `email` varchar(100) DEFAULT NULL,
  `media` varchar(200) NOT NULL,
  `country` varchar(200) NOT NULL
);
The HTML
<div class="contentArea">
<input type="text" class="search" id="inputSearch" />Ex: swadesh, ipsita, dharitri<br /> 
<div id="divResult">
</div>
</div>

The CSS
<style type="text/css">
        body{ 
                font-family: 'lucida grande', tahoma, verdana, arial, sans-serif;
        }
        .contentArea{
                width:600px;
                margin:0 auto;
        }
        #inputSearch
        {
                width:350px;
                border:solid 1px #000;
                padding:3px;
        }
        #divResult
        {
                position:absolute;
                width:350px;
                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: 3px 1px 1px;
                border-style: solid;
                border-color: #333 #DEDEDE #DEDEDE;
                background-color: white;
        }
        .display_box
        {
                padding:4px; border-top:solid 1px #dedede; 
                font-size:12px; height:50px;
        }
        .display_box:hover
        {
                background:#3bb998;
                color:#FFFFFF;
                cursor:pointer;
        }
</style>

The Javascript
$(function(){
$(".search").keyup(function() 
{ 
var inputSearch = $(this).val();
var dataString = 'searchword='+ inputSearch;
if(inputSearch!='')
{
      $.ajax({
      type: "POST",
      url: "search.php",
      data: dataString,
      cache: false,
      success: function(html)
      {
      $("#divResult").html(html).show();
      }
      });
}return false;    
});

jQuery("#divResult").live("click",function(e){ 
      var $clicked = $(e.target);
      var $name = $clicked.find('.name').html();
      var decoded = $("<div/>").html($name).text();
      $('#inputSearch').val(decoded);
});
jQuery(document).live("click", function(e) { 
      var $clicked = $(e.target);
      if (! $clicked.hasClass("search")){
      jQuery("#divResult").fadeOut(); 
      }
});
$('#inputSearch').click(function(){
      jQuery("#divResult").fadeIn();
});
});

The PHP Code

<?php
include('includes/db.php');
if($_POST)
{
$q=$_POST['searchword'];
$sql_res=mysql_query("select uid,username,email,media,country from test_auto_complete where username like '%$q%' or email like '%$q%' order by uid LIMIT 5");
while($row=mysql_fetch_array($sql_res))
{
$username=$row['username'];
$email=$row['email'];
$media=$row['media'];
$country=$row['country'];
$b_username='<b>'.$q.'</b>';
$b_email='<b>'.$q.'</b>';
$final_username = str_ireplace($q, $b_username, $username);
$final_email = str_ireplace($q, $b_email, $email);
?>
<div class="display_box" align="left">
<img src="<?php echo $media; ?>" style="width:50px; height:50px; float:left; margin-right:6px;" /><span class="name"><?php echo $final_username; ?></span>&nbsp;<br/><?php echo $final_email; ?><br/>
<span style="font-size:9px; color:#999999"><?php echo $country; ?></span></div>
<?php
}
}
?>

Fix

If you store firstname and lastname separately in your database, please update the line 

$sql_res=mysql_query("select uid,username,email,media,country from test_auto_complete where username like '%$q%' or email like '%$q%' order by uid LIMIT 5");

with the following

$sql_res=mysql_query("select uid,username,email,media,country from test_auto_complete where lower(concat_ws(' ', firstname, lastname)) like '%$q%' or email like '%$q%' order by uid LIMIT 5");