in this post we explained that how to create Autocomplete search or live search using php mysql and ajax without page refresh. that is some predefined texts come in the input type box while focus on textfield we are search some entered content from mysql database, actually this is a facebook style search.you can see live demo by click on live demo button and download by clicking on download button,
DB.PHP
<?php
$connection = mysql_connect('hostname','username','password') or die(mysql_error());
$database = mysql_select_db('databasename') or die(mysql_error());
?>
INDEX.PHP
<div class="content">
<input type="text" class="search" id="searchid" placeholder="Search for people" /> Ex:arunkumar, shanmu, vicky<br />
<div id="result"></div>
</div>
AJAX
<script type="text/javascript" src="jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(function(){
$(".search").keyup(function()
{
var searchid = $(this).val();
var dataString = 'search='+ searchid;
if(searchid!='')
{
$.ajax({
type: "POST",
url: "search.php",
data: dataString,
cache: false,
success: function(html)
{
$("#result").html(html).show();
}
});
}return false;
});
jQuery("#result").live("click",function(e){
var $clicked = $(e.target);
var $name = $clicked.find('.name').html();
var decoded = $("<div/>").html($name).text();
$('#searchid').val(decoded);
});
jQuery(document).live("click", function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("search")){
jQuery("#result").fadeOut();
}
});
$('#searchid').click(function(){
jQuery("#result").fadeIn();
});
});
</script>
SEARCH.PHP
<?php
include('db.php');
if($_POST)
{
$q=$_POST['search'];
$sql_res=mysql_query("select id,name,email from autocomplete where name like '%$q%' or email like '%$q%' order by id LIMIT 5");
while($row=mysql_fetch_array($sql_res))
{
$username=$row['name'];
$email=$row['email'];
$b_username='<strong>'.$q.'</strong>';
$b_email='<strong>'.$q.'</strong>';
$final_username = str_ireplace($q, $b_username, $username);
$final_email = str_ireplace($q, $b_email, $email);
?>
<div class="show" align="left">
<img src="author.PNG" style="width:50px; height:50px; float:left; margin-right:6px;" /><span class="name"><?php echo $final_username; ?></span> <br/><?php echo $final_email; ?><br/>
</div>
<?php
}
}
?>
if you have any question about php than you can freely can contact at
Email : easyscript4you@gmail.com
i like it
ReplyDeleteHi
ReplyDeleteIf you want, check this PHP - Ajax search script:
http://coursesweb.net/php-mysql/ssep-site-search-engine-php-ajax_s2
It has many features, like infinite / standard paginatin of search results, Autocomplete search, search score relevance, ...
Great post
ReplyDeletethanks
hire Magento Developer