Autocomplete in php ajax

autosuggest.html

<script type="text/javascript" src="//code.jquery.com/jquery-1.8.0.min.js"></script>
<script>
$(function(){
$("#search_emp").keyup(function()
{
var search_keyword_value = $(this).val();
var dataString = 'search_keyword='+ search_keyword_value;
if(search_keyword_value!='')
{
$.ajax({
type: "POST",
url: "search_emp.php",
data: dataString,
cache: false,
success: function(html)
{
$("#result_emp").html(html).show();
}
});
}
return false;
});

$("#result_emp").live("click",function(e){
var $clicked = $(e.target);
var $name = $clicked.find('.country_name').html();
var decoded = $("<div/>").html($name).text();
$('#search_keyword_id').val(decoded);
});

$(document).live("click", function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("search_keyword")){
$("#result_emp").fadeOut();
}
});

$('#search_keyword_id').click(function(){
$("#result_emp").fadeIn();
});
});

function set_emp(emp_name,emp_id) {
// change input value
$('#search_emp').val(emp_name);
$('#emp_id_search').val(emp_id);
// hide proposition list
$('#result_emp').hide();
}
</script>
<style>
#result_emp
{
position:relative;
width:320px;
display:none;
margin-top:-1px;
border-top:0px;
overflow:hidden;
border:1px #CDCDCD solid;
background-color: white;
}
.show
{
font-family:tahoma;
padding:10px;
border-bottom:1px #CDCDCD dashed;
font-size:15px;
}
.show:hover
{
background:#364956;
color:#FFF;
cursor:pointer;
}
</style>
<div class="form-group">
<label class="col-sm-2 control-label">Employee</label>
<div class="col-sm-10">
<input class="form-control" id="search_emp" name="emp" type="text" placeholder="" value="" autocomplete="off">
<input type="hidden" name="emp_id_search" id="emp_id_search" value="">
<div id="result_emp"></div>
</div>
</div>

search_emp.php

<?php
define("HOST_NAME" , "localhost");
define("DB_USER" , "root");
define("DB_PASS" , "");
define("DB_NAME" , "db");

mysql_connect(HOST_NAME,DB_USER,DB_PASS) or die(mysql_error());
mysql_select_db(DB_NAME);
if(isset($_POST['search_keyword']))
{
$search_keyword = $_POST['search_keyword'];
$bold_search_keyword = '<strong>'.$search_keyword.'</strong>';
$result=mysql_query("SELECT emp_id,emp_name FROM employees WHERE emp_name LIKE '%$search_keyword%'");
while ($emp_list=mysql_fetch_array($result))
{
echo '<div class="show" align="left" onclick="set_emp(\''.str_replace("'", "\'", $emp_list['emp_name']).'\',\''.str_replace("'", "\'", $emp_list['emp_id']).'\')"><span class="country_name">'.str_ireplace($search_keyword,$bold_search_keyword,$emp_list['emp_name']).'</span></div>';
}

}
?>

Share This:

Leave a Reply

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