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!

THANK YOU!

has been added to your cart!

Powered by Easy Digital Downloads

Thank you!

have been added to your cart!

Powered by Easy Digital Downloads

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.
Home jQuery

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 https://www.igloosoftware.com/product/integrations/org_chart_now/ (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.

Our Code Blog is Now Responsive!

Hey guys! How are you? I just want to have this quick post as an announcement that finally, our code blog is now responsive! The growth of mobile browsing is massive, and we want to keep up!Regarding the codes, I used the same principle with our post on how to code a responsive website. It might be a little harder if you're using a Google blogger platform, but you can do it if you're really determined! I was a little challenged but it was fun!

We also made this blog a little faster now, if you're interested, we'll have another post with a topic on how to make your website load faster based on our experience with this site.

Okay so now we'll give you some views as proof that our website is now responsive. See some screenshots below! Actually, you can also just test it yourself by re-sizing your browser window. Haha!

Read more