Simple AutoSuggestion Searchbox using jQuery Ajax and PHP

Code Sport 16 Feb , 2014  

Buffer

Hi All, Today we are talking about Autosuggestions . This is all about giving our users more comfort by autosuggestion. It is smart way to let them know that we understand them and their need.. Lets take a example of facebook… it is very easy to navigate to a friends page.. all you need to do is just type some initials of your friends name and hit enter key… So suppose you know the surname of your friend it will help you also..

auto_suggesion

downloadnow
Lets see how it works –

Step -1 : Database Creation –

CREATE TABLE IF NOT EXISTS `autosuggession_searchbox` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL,
`f_name` varchar(20) NOT NULL,
`l_name` varchar(20) NOT NULL,
`country` varchar(20) NOT NULL,
PRIMARY KEY (`ID`)
);

auto_suggesion

Step-2 : Index.php Page –

<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="jquery-1.10.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#search_box").keyup(function(){var search_string = $("#search_box").val();
if(search_string == ''){$("#searchres").html('');}else{postdata = {'string' : search_string}
$.post("check.php",postdata,function(data){ $("#searchres").html(data); });}});});
function fillme(name){$("#search_box").val(name);$("#searchres").html('');}
</script>
</head>
<body>
<div class="header"><input type="text" class="search_box" id="search_box" placeholder="Search Your Friends" autocomplete="off"></div>
<div id="searchres" class="searchres"></div>
</body>
</html>

auto_suggesion

Step-3 : Check.php file for Ajax call using jquery in index page

<?php
$con = mysql_connect(“localhost”,”root”,”");
mysql_select_db(‘projects’, $con) or die(“Could not connect to Server”);
if(isset($_POST['string'])){
$s = mysql_real_escape_string($_POST['string']);
$query = “select * from autosuggession_searchbox where f_name like ‘%$s%’ || l_name like ‘%$s%’ || CONCAT(f_name, ‘ ‘,l_name) like ‘%$s%’ order by ID limit 5″;
$res = mysql_query($query);
if(mysql_num_rows($res)>0){
while($row = mysql_fetch_object($res)){?>
<a target=”_blank” href=”http://www.facebook.com/<?php echo $row->username;?>” onclick=”fillme(‘<?php echo $row->f_name.” “.$row->l_name;?>’);”>
<div class=”user_div”>
<img src=”imgs/<?php echo $row->ID;?>.png” style=”border-radius:5px;float:left;”>
<div class=”name”><?php echo $row->f_name?> <?php echo $row->l_name;?></div><br><div class=”cntry”><?php echo $row->country;?></div>
</div>
</a>
<?php }
}else{?>
<div class=”no_data”>No Result Found !</div>
<?php }
}
?>

downloadnow

This is all . All you need to do now is just save these files and run the script. Any question? let me know using following comment box. Stay tuned and be better for more interesting codes..

, , ,