Home jQuery

jQuery UI Autocomplete Example

We, the developers, want to help our users search for the data they are looking for – in an easy manner. This jQuery UI autocomplete tutorial will help you achieve it!

Having an autocomplete feature in our search box is really good for the user experience, it is like having a user assistant while he is trying to search.

Our code for today will make use of a textbox where the user can type his search term. The sample data we use are person names (firstname and lastname).

So, when the user types a name, our program will suggest some names that might be what the user is looking for.

Contents:

1.0 Project Files
2.0 Database
3.0 The User Interface
4.0 Getting Search Results
4.1 JSON Data
5.0 Adding Some Style
6.0 Download Source Code

1.0 Project Files

Our code for today includes the following files:

libs/db_connect.php
images/ajax-loader.gif
css/style.css
index.php
results.php

2.0 Database

The table structure used and some sample data were provided below:

--
-- Table structure for table `users`
--

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `firstname` varchar(32) NOT NULL,
  `lastname` varchar(32) NOT NULL,
  `gender` varchar(6) NOT NULL,
  `email` varchar(32) NOT NULL,
  `username` varchar(32) NOT NULL,
  `password` varchar(32) NOT NULL,
  `created` datetime NOT NULL,
  `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=76 ;

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`id`, `firstname`, `lastname`, `gender`, `email`, `username`, `password`, `created`, `modified`) VALUES
(49, 'Justine', 'Bongola', 'Male', 'justine@coanmail.com', 'jaja', 'jaja123', '0000-00-00 00:00:00', '2013-03-03 14:06:03'),
(51, 'Lourd', 'De Veyra', 'Male', 'lourd@coanmail.com', 'lourd', 'lourd123', '0000-00-00 00:00:00', '2013-03-03 14:06:03'),
(73, 'Mike', 'Dalisay', '', '', 'ninjazhai', 'allisfine', '0000-00-00 00:00:00', '2013-05-12 06:39:04'),
(74, 'Darwin', 'Dalisay', '', '', 'dada', 'dada123', '0000-00-00 00:00:00', '2013-05-12 06:39:24'),
(75, 'Marykris', 'Dalisay', '', '', 'mary143', 'mary123', '0000-00-00 00:00:00', '2013-05-13 16:51:14');

Here’s how we connect to the database, just change the variable values that will make you connected to your database.

<?php
$host = "yourHost";
$db_name = "yourDatabaseName";
$username = "yourDatabaseUsername";
$password = "yourPassword";

try {
    $con = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
}catch(PDOException $exception){ //to handle connection error
    echo "Connection error: " . $exception->getMessage();
}
?>

3.0 The User Interface

index.php – this is where the user can find the textbox, tries to type on it and our system suggests some keywords as autocomplete, and this is also where we include our jQuery UI theme and jQuery scripts.

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>jQuery UI auto-complete tutorial live demo</title>

		<!-- include the jquery ui theme css and your own css -->
		<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.0/themes/smoothness/jquery-ui.css" />
		<link rel="stylesheet" href="css/style.css" />

    </head>
<body>

<!--
	-this is our text box, we didn't use type='text' but type='search' instead
	 to have a clear (x) function in case a user wants to easily remove what's in the textbox
	-placeholder='Search firstname or lastname' - is an HTML5 attribute the can give your
	 users a clue on what to search or type in the textbox
-->
<div>Try to type "dalisay" below:</div>
<input type='search' id='nameSearch' placeholder='Search firstname or lastname' />

<!--
	-now we'll include the jQuery and jQuery UI libraries
-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.0/jquery-ui.min.js"></script>

<script type="text/javascript">
$(document).ready(function(){

	// this is how to add autocomplete functionality in a textbox
	// source:'results.php' - where it will pass the search term and generates the JSON data
	// minLength:1 - how many characters user enters in order to start search
	$('#nameSearch').autocomplete({

		source:'results.php',
		minLength:1,
		select: function(event, ui){

			// just in case you want to see the ID
			var accountVal = ui.item.value;
			console.log(accountVal);

			// now set the label in the textbox
			var accountText = ui.item.label;
			$('#nameSearch').val(accountText);

			return false;
		},
		focus: function( event, ui ) {
			// this is to prevent showing an ID in the textbox instead of name
			// when the user tries to select using the up/down arrow of his keyboard
			$( "#nameSearch" ).val( ui.item.label );
			return false;
		},

   });

});
</script>

</body>
</html>

4.0 Getting Search Results

results.php – this is where the search term were passed, queries the database and generates the JSON data needed to show the autocomplete terms in the user interface.

<?php
// connect to the database
include "libs/db_connect.php";

// get the search term
$search_term = isset($_REQUEST['term']) ? $_REQUEST['term'] : "";

// write your query to search for data
$query = "SELECT 
            id, firstname, lastname 
        FROM 
            users 
        WHERE 
            firstname LIKE "%{$search_term}%" OR 
            lastname LIKE "%{$search_term}%" 
        LIMIT 0,10";

$stmt = $con->prepare( $query );
$stmt->execute();

// get the number of records returned
$num = $stmt->rowCount();

if($num>0){ 

    // this array will become JSON later
    $data = array();

    // loop through the returned data
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
        extract($row);

        $data[] = array(
            'label' => $firstname . " " . $lastname,
            'value' => $id
        );
    }

    // convert the array to JSON
    echo json_encode($data);

}

//if no records found, display nothing
else{
    die();
}
?>

4.1 Wondering how the returned JSON data looks like?

[
  {
    "label": "Mike Dalisay",
    "value": "28"
  },
  {
    "label": "Darwin Dalisay",
    "value": "40"
  }
]

You can also take a look at your own JSON data by browsing your results.php?term=your_search_term

5.0 Adding Some Styles

style.css – this is where you can change the loading GIF image and add some style to our textbox.

.ui-autocomplete-loading {
    /* you can replace ajax-loader.gif with another gif image you want for your design */
    background: white url('images/ajax-loader.gif') right center no-repeat;
}

/* some style for our textbox */
#nameSearch{
    padding:.5em;
    width:20em;
}

6.0 Download Source Code

You can download all the code used in this tutorial for only $9.99 $5.55!

Congratulations! Now you can make your users happier by this search assistant feature, and as always, thanks for reading!