jQuery Autocomplete with Highlight Text and Ajax/PHP

3 min read

OK Here’s a working example for those who are looking… The script grabs autocomplete results from search.php and highlights matches… not just at the beginning of the result but anywhere in the word the match occurs.

Header:

This script sends a request to search.php using the variable $_GET[‘term’].

1
2
3
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<script>
 
      function monkeyPatchAutocomplete() {
 
          var oldFn = $.ui.autocomplete.prototype._renderItem;
 
          $.ui.autocomplete.prototype._renderItem = function( ul, item) {
 
              var t = String(item.value).replace(
                new RegExp(this.term, "gi"),
                "<span class='ui-state-highlight'>$&</span>");
 
              return $( "<li></li>" )
                  .data( "item.autocomplete", item )
                  .append( "<a>" + t + "</a>" )
                  .appendTo( ul );
          };
      }
 
  $(function() {
 
        function log( message ) {
            $( "<div>" ).text( message ).prependTo( "#log" );
            $( "#log" ).scrollTop( 0 );
        }
 
         monkeyPatchAutocomplete();
 
        $( "#search" ).autocomplete({
            source: "path/to/search.php",
            minLength: 1,
            select: function( event, ui ) {
                log( ui.item ?
                    "Selected: " + ui.item.value + " aka " + ui.item.id :
                    "Nothing selected, input was " + this.value );
            }
        });
    });
</script>

Body

1
<input type="text" name="search" id="search" />

Ajax

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
< ?
/*** connect to your DB here ***/
 
//retrieve the search term and strip and clean input
$term = trim(strip_tags($_GET['term'])); 
if (!$term ) return;
 
//try to make user input safer
$term = mysql_real_escape_string($term);
 
//build a query on the database
$sql = "SELECT *  FROM `".$db_name."`.`".$db_table_prefix."Table` WHERE `Field` LIKE '%$term%' ORDER BY Field ASC ";
 
//query the database for entries containing the term
$result = mysql_query($sql);
 
while ($row = mysql_fetch_array($result,MYSQL_ASSOC))//loop through the retrieved values
{
		$row['value']=htmlentities(stripslashes($row['Field']));
		$row['id']=(int)$row['ID'];
		$row['field3']=(int)$row['Field3']; // you can pass back multiple fields
		$row_set[] = $row; //build an array
}
 
//format the array into json data
echo json_encode($row_set);
 
?>