The common and necessary function that we usually see on almost websites is about searching suggestion. Auto suggestion is very useful and convenient for the users when they are trying to find something in a website by just typing some keywords in the searching box normally placed right in the website header block. Then, the suggested keywords are listed down as the drop down list right below the searching box helping users to use the right keyword to get the desired result. There are some options that we can show the drop down data list by showing the recent keywords, popular keywords, recommended keywords, sorted keywords, etc. Actually, there are many libraries or free script that can be implemented to our website. However, having our own functions is the most preferable way of being the challenging web developer. Therefore, in this tutorial, we show the auto suggested data by recent keywords (order by datetime).
CREATE TABLE IF NOT EXISTS ` tblkeywords` ( `id` int(11) NOT NULL AUTO_INCREMENT, `keyword` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `totalhit` int(11) COLLATE utf8_unicode_ci NOT NULL, `datetime` Datetime COLLATE utf8_unicode_ci NOT NULL, `active ` int(1) NOT NULL DEFAULT '1', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
We need to have a table to store the keywords searched by the users when they do their searching. Now, we name that table as tblkeywords with some important rows like id, keyword, totalhit, datetime, and active. Please be noted that the database structure can be various depends on what we really to do with it.
#search_suggest_box{ display:none;position:relative; left:12px; top:33px; width:133px; height:auto; text-align:left; border-radius:0 0 5px 5px; color:#fff; z-index:100;box-shadow:0 0 1px 0 #9d9d9d; border:1px solid #ebebeb; background: rgb(255,255,255); background: -moz-linear-gradient(top, rgba(255,255,255,1) 0%, rgba(229,229,229,1) 100%); background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(255,255,255,1)), color-stop(100%,rgba(229,229,229,1))); background: -webkit-linear-gradient(top, rgba(255,255,255,1) 0%,rgba(229,229,229,1) 100%); background: -o-linear-gradient(top, rgba(255,255,255,1) 0%,rgba(229,229,229,1) 100%); background: -ms-linear-gradient(top, rgba(255,255,255,1) 0%,rgba(229,229,229,1) 100%); background: linear-gradient(to bottom, rgba(255,255,255,1) 0%,rgba(229,229,229,1) 100%); filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#e5e5e5',GradientType=0 ); } #search_suggest_list{ padding:3px 5px; } .search_suggest_item{ padding:3px; font-size:11px; color:blue; border-top:1px dotted #e4d6f5; } .search_suggest_item:hover{ color:white; cursor:pointer; background:#c0a0e9; }
In the style file (CSS file), we just do some styling for the drop down list and its items. Because it’s just the basic style, we can adjust the style of the searching box and the drop down list as what we want.
function searchSuggestionList(){ $("#search_suggest_list").html('<span style="color:blue;">Loading...</span>'); $.post("/includes/getData.php",{searchKeyword:$("#searchInput").val()} ,function(data){ $("#search_suggest_list").html(data); }); } function selectSuggest(d){$("#searchInput").val(d);} function displaySearchSuggest(a){ if(a==1){$("#search_suggest_box").show();}else{$("#search_suggest_box").hide();} } $(document).ready(function(e) { $('#searchInput').keyup(function(e) {if (e.which != '13') {searchSuggestionList();}}); $('#searchInput').focus(function(e) {displaySearchSuggest(1);}); $('#searchInput').blur(function(e) {displaySearchSuggest(0);}); });
We have three JavaScript functions:
We need to set some events for search input box and in this case we use three events:
To make it works properly, please be noted that we need to place the input event handling in the document ready function as shown above.
$dbhost = "localhost"; $dbuser = "khcoder"; $dbpass = "khcoder***"; $dbname = "khcoder"; $conn = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname) or die("Error " . mysqli_error($conn)); $searchKeyword = $_POST['searchKeyword']; $suggestedList = ''; $keywords_qry= exec_query_utf8("SELECT * FROM tblkeywords WHERE keyword LIKE '%$searchKeyword%' AND active=1 ORDER BY datetime DESC LIMIT 7"); while($keywords_row=mysqli_fetch_assoc($keywords_qry)){ $keywords = $keywords_row['keyword']; $highlighted_keywords = preg_replace('/'.str_replace(' ','|', $searchKeyword).'/i', '<span style="background:#60b6c5;">$0</span>', $keywords); $suggestedList .= '<div class="search_suggest_item" onMouseOver="selectSuggest(''.$keywords.'')">'.$highlighted_keywords.'</div>'; } echo $suggestedList;
This is the core process of querying data back to the suggested list. In this section, to do the data query, we need to have the database connection by doing the connection configuration. However, we recommend using MySQL UTF8 Connection Using PHP, a useful function for query the UTF8 data.
Once we have the database connection, now it is time to do the query as shown above. We have a string variable to store the data list string to return to the requesting JS function. To make it more convenient, we use the function preg_replace for highlight the typed characters.
<div id="search_box_cover"> <div style="width:0;height:0;"> <div id="search_suggest_box"> <div id="search_suggest_list"></div> </div> </div> <input id="searchInput" type="search" placeholder="Search" /><div id="search_btn"></div> </div>
Now we have all the required functions and styles and this section is about html elements needed. Actually, it is not necessary that we have to use PHP file where HTML file is also fine. Here, we create some elements like suggested list block, search input box, and search input button as shown above.
Now, every required functions and inputs are built and created. We hope this tutorial will be helpful!!!