PHP: How to Implement jQuery Autocomplete using a JSON datasource CodeUnit 12 AUG 2011

The jQuery UI library is really useful in that it packages a number of jQuery-driven interactions, widgets, effects and utilities into a single package, ready for smooth integration and even easier deployment. One of the many available widgets in the jQuery UI library is Autocomplete, which makes adding autocomplete functionality to an ordinary text searchbox a doddle!

Let’s have a look how to implement this when using PHP to provide us with a separate JSON datasource then, shall we?

First, if your web page contains a normal textbox within a form that is used to conduct searches, you need to attach the jQuery UI autocomplete functionality with the following code snippet:

            source: "ajax-search-autocomplete.php",
            minLength: 2});

Note the minLength setting of 2. It is often useful to set the number of characters needed to initiate the search so as to minimize the possible amount of search return values for efficiency’s sake.

As you can see, we have prompted the autocomplete widget to make use of a file called ajax-search-autocomplete.php as a datasource. This file should look something like this:

//… all your database setup stuff
$searchresults = array();
$searchterm = (key_exists('term', $_GET)) ? $_GET['term'] : '';

if (strlen($searchterm) > 0) {
    $results = mysql_query("SELECT `name`  FROM `myTable` WHERE `name` LIKE '%$searchterm%' ORDER BY `name` ASC");
    while ($result = mysql_fetch_assoc($results)) {
        $searchresults[] = $result['filter-name'];
$searchresults = array_map("html_entity_decode_custom", $searchresults);
$searchresults = array_map("get_correct_utf8_mysql_string", $searchresults);
echo json_encode($searchresults);

And that is it. Load it up and try it out, and hey presto, you now have a nifty autocomplete that took you almost no time to implement! :)

Related Link:

Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.