Auto-complete with JQuery

Posted on Aug 25th, 2009 At 12:41 am by baldo

Recently I coded a JQuery version of a feature I've been using in some projects. Basically this feature is a PHP script that queries a MySQL database and displays a list of possible input keywords using AJAX. It is based on the idea of Google suggest.

Here is an example:

Here is the code to accomplish that fancy behaviour.

Note: I´m using the world database, you can download it from the MySql documentation


autocomp.php

    1 <?php
    2    $USER = "someuser";
    3    $PASS = "somepass";
    4 
    5    $conn =  mysql_connect("localhost", $USER, $PASS);
    6   // R�union  = Réunion
    7    mysql_query("SET NAMES 'utf8'");
    8    mysql_select_db("world",$conn);
    9 
   10    //trim searchKeyword
   11    $searchKeyword = trim($_POST["searchKeywordTmp"]);
   12   //clean searchKeyword
   13    $searchKeyword = mysql_real_escape_string($searchKeyword, $conn);
   14 
   15    if(isset($searchKeyword) && ($searchKeyword)){
   16        $query = "SELECT Name FROM Country";
   17        $query .= " WHERE Name LIKE '$searchKeyword%' LIMIT 5";
   18        if($result = mysql_query($query)){
   19             $flag = 0;
   20             while($dataArray = mysql_fetch_array($result)){
   21                  $data = $dataArray["Name"]; ?>
   22                  <li onclick="fill('<?php echo $data; ?>');">
   23 			<?php echo $data; ?>
   24                  </li><?php
   25                  $flag = 1;
   26               }
   27               if($flag == 0)
   28                  echo "Your search keyword is incorrect."; //empty query
   29         } else
   30              echo mysql_error();
   31     }else echo "ERR";
   32 ?>

suggest.js

    1 var flag = 1;
    2 
    3 function suggest(searchKeyword){
    4    //using ajax and jquery for asynchronous update
    5    $.post("autocomp.php", {searchKeywordTmp: ""+searchKeyword+""},
    6        function(data){
    7           if(data == "ERR")
    8              $("#suggestions").hide();
    9           else{
   10 		    $("#suggestions").show();
   11 		    $("#suggestionsList").html(data);
   12           }
   13        }
   14    );
   15 }//end function suggest
   16 
   17 function fill(thisValue) {
   18    $("#searchBox").val(thisValue);
   19    $("#suggestions").hide();
   20 }//end function fill
   21 
   22 //disable browser' auto-complete
   23 function disAutoComplete(obj){
   24     if(flag){
   25   	obj.setAttribute("autocomplete","off");
   26          flag = 0;
   27     }
   28     window.location = "#tc";
   29     obj.focus();
   30 }

suggest.html

    1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    2     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    3 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" dir="ltr">
    4 <head>
    5 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    6 <link rel='stylesheet' type='text/css' href='style.css' media='screen'/>
    7 <script src="js/jquery-1.3.2.js" type="text/javascript"></script>
    8 <script src="js/suggest.js" type="text/javascript" ></script>
    9 </head>
   10 <body>
   11    <p>
   12      <b>
   13        <span id="tc">Type a country name:</span>
   14      </b>
   15    </p>
   16    <input size="30" type="text" id="searchBox" onkeyup="suggest(this.value);"
   17     onclick="disAutoComplete(this);" />
   18    <div class="suggestionsBox" id="suggestions" style="display: none;">
   19 	    <img src="img/upArrow.png" alt="upArrow"
   20         style="position: relative; top: -10px; left: 30px" />
   21 	    <div  class="suggestionsList" id="suggestionsList"></div>
   22    </div>
   23 </body>
   24 </html>

Update:

The example has been changed to save resources in the new server, now I use a screenshot.

Category: PHP, MySQL, AJAX, JQuery