jQuery UI Autocomplete Example

(adsbygoogle = window.adsbygoogle || []).push({});

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.


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:


2.0 Database

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

-- Table structure for table `users`

  `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,
  PRIMARY KEY (`id`)

-- Dumping data for table `users`

INSERT INTO `users` (`id`, `firstname`, `lastname`, `gender`, `email`, `username`, `password`, `created`, `modified`) VALUES
(49, 'Justine', 'Bongola', 'Male', '', 'jaja', 'jaja123', '0000-00-00 00:00:00', '2013-03-03 14:06:03'),
(51, 'Lourd', 'De Veyra', 'Male', '', '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.

$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.

        <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="" />
		<link rel="stylesheet" href="css/style.css" />


	-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=""></script>
<script src=""></script>

<script type="text/javascript">

	// 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

		select: function(event, ui){

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

			// now set the label in the textbox
			var accountText = ui.item.label;

			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;




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.

// 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 
            firstname LIKE "%{$search_term}%" OR 
            lastname LIKE "%{$search_term}%" 
        LIMIT 0,10";

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

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


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

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

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

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


//if no records found, display nothing

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 */

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!


Code Ultra Fast with Emmet

Hey guys! Today we have a guest post from our friend Aditya Kanodia. This post is so cool that you can code a whole HTML page with just a single line of code, no exaggeration!. So keep on reading below! ~ Mike
Have you ever wished to code your websites really fast? If yes, then Emmet is just the right thing for you! Emmet is an extension made for your code editors to simplify your coding work.

So, in this article I will be showing how to get Emmet for your favorite editor and work with it.

Google said “The web should be fast”: How to Optimize Your Website for Speed

Hey guys! Today we have a guest post about some tips on how to speed up your website! He’s currently working for an e-commerce website and one of his tasks is to make the site load fast. So enjoy reading below! ~ Mike
Website speed becomes an obsession of search engines like Google and one of the reasons is the rapid growth of mobile internet browsing. If you’re working with the (developers, designers, bloggers and students), it is now a requirement to have knowledge in making a website load fast, and our post for today will give you some ideas on why and how to achieve it.