The jQuery UI Autocomplete plugin provides an instant way to add autocomplete suggestions feature to the textbox. It allows the user to quickly search and select a value from a pre-populated list. When the user starts typing in the input field, the Autocomplete plugin fetches the matched values and listed them under the textbox. You can easily integrate the autocomplete textbox functionality using jQuery UI, PHP, and MySQL.
Generally, the Autocomplete widget fetch the values from the database and display the suggestions in text format under the input field. But, you can customize the autocomplete dropdown and suggestions list with custom HTML code. The custom autocomplete dropdown list is very useful when you want to maintain the design with the webpage layout. In this tutorial, we will show you how to add custom HTML and show images and text in autocomplete suggestions list dropdown using jQuery UI, PHP, and MySQL.
In the example script, we will integrate an auto-suggestions textbox for members’ search input, and display images and text in the autocomplete drop-down.
To store the autosuggestions data a table needs to be created in the database. The following SQL creates a users
table with some basic fields in the MySQL database.
CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `first_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL, `last_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL, `image` varchar(150) COLLATE utf8_unicode_ci NOT NULL, `created` datetime NOT NULL, `modified` datetime NOT NULL, `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active | 0=Inactive', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
JavaScript Code:
Include the jQuery and jQuery UI library files to use the Autocomplete plugin.
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<!-- jQuery UI library -->
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.13.2/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.13.2/jquery-ui.min.js"></script>
Use the autocomplete() method to initialize the jQuery UI Autocomplete plugin.
source
– Specify the path of the server-side script to fetch the dynamic data from the database.minLength
– The minimum number of characters the user must type to perform the searchselect
– This event is triggered when an item is selected from the suggestions dropdown.
_renderItem
– The renderItem extension helps to customize the autocomplete widget.
<script> $(document).ready(function(){ $("#searchInput").autocomplete({ source: "fetchUsers.php", minLength: 1, select: function(event, ui) { $("#searchInput").val(ui.item.value); $("#userID").val(ui.item.id); } }).data("ui-autocomplete")._renderItem = function( ul, item ) { return $( "<li class='ui-autocomplete-row'></li>" ) .data( "item.autocomplete", item ) .append( item.label ) .appendTo( ul ); }; }); </script>
HTML Code:
Define an HTML input element to attach the Autocomplete feature.
<!-- Autocomplete input field --> <input id="searchInput" placeholder="Enter member name..." autocomplete="off"> <!-- Hidden input to store selected user's ID --> <input type="hidden" id="userID" name="userID" value=""/>
The dbConfig.php
file is used to connect and select the database. Specify the database host ($dbHost
), username ($dbUsername
), password ($dbPassword
), and name ($dbName
) as per your MySQL server credentials.
<?php
// Database configuration
$dbHost = "localhost";
$dbUsername = "root";
$dbPassword = "root";
$dbName = "codexworld";
// Create database connection
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
The fetchUsers.php
is loaded by the autocomplete() method of the jQuery UI Autocomplete plugin.
fetchUsers.php
) and adds a term parameter in the query string. users
table) using PHP and MySQL.<?php
// Include database config file
require_once 'dbConfig.php';
// Get search term
$searchTerm = $_GET['term'];
// Get matched data from the database
$query = "SELECT id, first_name, last_name, image FROM users WHERE (first_name LIKE '%".$searchTerm."%' OR last_name LIKE '%".$searchTerm."%') AND status = 1 ORDER BY first_name ASC";
$result = $db->query($query);
// Generate array with user's data
$userData = array();
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$name = $row['first_name'].' '.$row['last_name'];
$data['id'] = $row['id'];
$data['value'] = $name;
$data['label'] = '
<a href="javascript:void(0);">
<img src="images/users/'.$row['image'].'" width="50" height="50"/>
<span>'.$name.'</span>
</a>
';
array_push($userData, $data);
}
}
// Return results as json encoded array
echo json_encode($userData);
?>
Autocomplete Textbox with Multiple Selection using jQuery in PHP
If you want to integrate autocomplete search input functionality, this jQuery Autocomplete textbox with images is very useful to make the search textbox user-friendly. The example code shows you to add images, text, and custom HTML in the autocomplete widget. You can easily extend this script to customize the autocomplete dropdown and render HTML elements. For the example of various configuration options of the jQuery UI Autocomplete plugin, see this tutorial – Autocomplete Textbox using jQuery, PHP and MySQL
Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request
Great code. Very helpful. Thank you for sharing this.
Thank you very much! I never comment on these tutorials but you saved me hours of searching, testing and switching between bootstrap and query typeahead. Thank you! It works beautifully.
jQuery UI Autofill with images and custom HTML Hi, your article was useful and effective about PHP.