jQuery Autocomplete with Highlight Text and Ajax/PHP

< 1 min read
Reading Time: < 1 minute

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.


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



< ?
/*** 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['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);