How to jQuery UI Autocomplete with Images and Custom HTML in PHP

How to jQuery UI Autocomplete with Images and Custom HTML in PHP

How to jQuery UI Autocomplete with Images and Custom HTML in PHP

0 Sales


The jQuery UI Autocomplete plugin adds autocomplete recommendations to the textbox in an instant. It enables the user to swiftly search for and choose a value from a pre-populated list. When the user begins typing in the input field, the Autocomplete plugin retrieves the matching values and displays them in the textbox. Using jQuery UI, PHP, and MySQL, you can quickly implement the autocomplete textbox capability.

In general, the Autocomplete widget retrieves values from the database and displays them as text recommendations beneath the input box. Custom HTML code, on the other hand, may be used to alter the autocomplete dropdown and recommendations list. When you wish to keep the aesthetic of the webpage layout, the custom autocomplete dropdown list comes in handy. In this article, we'll teach you how to use jQuery UI, PHP, and MySQL to add custom HTML to display pictures and text in autocomplete.

In the sample script, we will include an auto-suggestions textbox for member searches, as well as photos and text in the autocomplete drop-down menu.

 - To search for members by name, use the autocomplete textbox.
 - When the user begins typing in the input field, the data for the matched members is retrieved from the database.
 - In the auto recommendations option, the member's info, including name and photograph, will be listed.

Create Database Table

A table in the database must be built to contain the autosuggestions data. In the MySQL database, the below SQL generates a users table with some basic columns.

CREATE TABLE `users` (
 `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',
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Autocomplete Textbox

JavaScript Code:

To utilise the Autofill plugin, have included jQuery and jQuery UI library files.

<!-- jQuery library -->
<script src="jquery-ui/jquery/jquery.min.js"></script>

<!-- jQueryUI library -->
<link rel="stylesheet" href="jquery-ui/jquery-ui.css">
<script src="jquery-ui/jquery-ui.js"></script>

To initialise the jQuery UI Autocomplete plugin, use the autocomplete() function.

 - source – Enter the path of the server-side script that will retrieve dynamic data from the database.
  - minLength – The minimum amount of characters required by the user to do the search.
 - select – When an item is picked from the recommendations menu, this event is triggered.

      - When you choose an object, the value is set to the autocomplete input field and the user ID is assigned to the hidden input field.

 - _renderItem – The renderItem plugin aids in the customization of the autocomplete widget.

      - For each item in the auto-suggestions list, define a custom class.
      - Render the images and text in the widget's recommendation list with custom HTML.

        source: "getUsers.php",
        minLength: 1,
        select: function(event, ui) {
    }).data("ui-autocomplete")._renderItem = function( ul, item ) {
    return $( "<li class='ui-autocomplete-row'></li>" )
        .data( "item.autocomplete", item )
        .append( item.label )
        .appendTo( ul );

HTML Code:

Define an HTML input element to which the Autocomplete functionality will be attached.

 - When the user begins typing, the server-side source is queried for recommendations, and an autocomplete drop-down appears underneath the input box.
 - When a user picks an item from the auto-suggestion list, the ID associated with that item is allocated 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 for user ID -->  
<input type="hidden" id="userID" name="userID" value=""/>

Database Configuration (dbConfig.php)

To connect to and choose the database, utilise the dbConfig.php file. As per your MySQL server credentials, provide the database host ($dbHost), username ($dbUsername), password ($dbPassword), and name ($dbName).

// 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 (getUsers.php)

The autocomplete() function of the jQuery UI Autocomplete plugin loads getUsers.php.

 - The autocomplete() function sends a GET request to the source URL (getUsers.php) and inserts the term parameter into the query string.
 - To get the value of the search query, use the PHP $_GET method.
 - Using PHP and MySQL, retrieve the matching user's data (filtered by search phrase) from the database (users table).
 - Add a user picture, first name, and last name to the label using HTML elements.
 - Make an array out of the filtered data.
 - Data from filtered users is shown in JSON format.

// 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 users data array
$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"/>

// Return results as json encoded array
echo json_encode($userData);


If you wish to incorporate an users search function, this jQuery Autofill textbox with photos can help you make the search field more user-friendly. The example code demonstrates how to include photos, text, and customized HTML in the auto - complete widget. This script may be simply extended to personalise the autocomplete selection and render HTML components.


You can use it for personal or commercial projects. You can't resell it partially or in this form.


Create Date : Feb 17, 2022

Updated Date : Feb 17, 2022


Comments : 0

Downloads : 0