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.
Header:
This script sends a request to search.php using the variable $_GET[‘term’].
Body
Ajax
< ?
/*** 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);
?>
tech ajax autocomplete highlight jquery php
8 March, 2014 @ 6:44 am
This was great! A simple solution I have been looking for!
4 September, 2016 @ 10:47 pm
Thank you. Perfect.