Thursday, June 29, 2017
Home » PHP » Creating Autocomplete or Search Suggestion Functionality with PHP and MySQL

Creating Autocomplete or Search Suggestion Functionality with PHP and MySQL

 

 

index.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title> jQuery PHP Ajax Autosuggest</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script>
function suggest(inputString){
if(inputString.length == 0) {
$('#suggestions').fadeOut();
} else {
$('#country').addClass('load');
$.post("autosuggest.php", {queryString: ""+inputString+""}, function(data){
if(data.length >0) {
$('#suggestions').fadeIn();
$('#suggestionsList').html(data);
$('#country').removeClass('load');
}
});
}
}

function fill(thisValue) {
$('#country').val(thisValue);
setTimeout("$('#suggestions').fadeOut();", 600);
}
</script>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<form id="form" action="#">
<div id="suggest">Start to type a country: <br />
<input type="text" size="25" value="" id="country" onkeyup="suggest(this.value);" onblur="fill();" class="" />

<div id="suggestions" style="display: none;"> <img src="arrow.png" style="position: relative; top: -12px; left: 30px;" alt="upArrow" />
<div id="suggestionsList"> &nbsp; </div>
</div>
</div>
</form>
</body>
</html>
style.css

#result {
    height:20px;
    font-size:16px;
    font-family:Arial, Helvetica, sans-serif;
    color:#333;
    padding:5px;
    margin-bottom:10px;
    background-color:#FFFF99;
}
#country{
    padding:3px;
    border:1px #CCC solid;
    font-size:17px;
}
.suggestionsBox {
    position: absolute;
    left: 0px;
    top:40px;
    margin: 26px 0px 0px 0px;
    width: 200px;
    padding:0px;
    background-color: #000;
    border-top: 3px solid #000;
    color: #fff;
}
.suggestionList {
    margin: 0px;
    padding: 0px;
}
.suggestionList ul li {
    list-style:none;
    margin: 0px;
    padding: 6px;
    border-bottom:1px dotted #666;
    cursor: pointer;
}
.suggestionList ul li:hover {
    background-color: #FC3;
    color:#000;
}
ul {
    font-family:Arial, Helvetica, sans-serif;
    font-size:11px;
    color:#FFF;
    padding:0;
    margin:0;
}

.load{
background-image:url(loader.gif);
background-position:right;
background-repeat:no-repeat;
}

#suggest {
    position:relative;
}