jQuery UI Autocomplete with Images and Custom HTML in PHP

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.

  • Autocomplete textbox to search the members by name.
  • When the user starts typing in the input field, the matched members’ data will be fetched from the database.
  • The member’s data with name and image will be listed in the auto-suggestions dropdown.

Create Database Table

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;

Autocomplete Textbox

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 search
  • select – This event is triggered when an item is selected from the suggestions dropdown.
    • On selecting an item, the value will be set to the autocomplete input field and user ID will be set to the hidden input field.
  • _renderItem – The renderItem extension helps to customize the autocomplete widget.
    • Define a custom class for each item of the auto-suggestions list.
    • Render the images and text with custom HTML in the suggestion list of the 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.

  • When the user starts typing, the suggestions are retrieved from the server-side source, and autocomplete drop-down will appear under the input field.
  • Once the user selects an item from the auto-suggestion list, the respective ID is assigned to a hidden input field (userID) for the form submission process.
<!-- 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=""/>

Database Configuration (dbConfig.php)

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);
}

Autocomplete Data with Images and Custom HTML (fetchUsers.php)

The fetchUsers.php is loaded by the autocomplete() method of the jQuery UI Autocomplete plugin.

  • The autocomplete() method makes a GET request to the source URL (fetchUsers.php) and adds a term parameter in the query string.
  • Use PHP $_GET method to retrieve the value of the search term.
  • Fetch the matched user’s data (filter by search term) from the database (users table) using PHP and MySQL.
  • Add user image, first name, and last name with HTML elements to the label.
  • Generate an array with the filtered data.
  • Render filtered users data in JSON format.
<?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

Conclusion

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

3 Comments

  1. Ricku Panthi Said...
  2. Cody Said...
  3. شهریار باغ فروش Said...

Leave a reply

keyboard_double_arrow_up