jQuery UI Autocomplete with Images and Custom HTML in PHP

jQuery UI Autocomplete with Images and Custom HTML in PHP

jQuery UI Autocomplete with Images and Custom HTML in PHP

The jQuery UI Autocomplete plugin offers you a quick way to add autocomplete suggestions feature to the textbox. It permits the user to search and select a value from a pre-populated list quickly. Therefore, when the user starts to type in the input field, the Autocomplete plugin fetches the matched values and lists them under the textbox. You can integrate the autocomplete textbox functionality using jQuery UI, PHP, and MySQL.

Typically, the autocomplete widget retrieves values ​​from the database and displays the suggestions as a text format under the input field. However, you can customize the autocomplete dropdown and suggestion list with custom HTML code. The custom autocomplete dropdown list is helpful when you want to maintain the design with a webpage layout. In this tutorial, we will show you how to add custom HTML and display images and text in autocomplete using jQuery UI, PHP, and MySQL.

In the sample script, we will integrate an auto-suggestions textbox for members’ search, and display images and text in the autocomplete drop-down.

Make a Database Table

To store the autosuggestions data, you need to create a table that needs to in the database. The following SQL creates a user table with some necessary 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:

Add the jQuery and jQuery UI library files to use the Autocomplete plugin.

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

Use the autocomplete() method to adjust the jQuery UI Autocomplete plugin.

<script>
$(document).ready(function(){
    $("#searchInput").autocomplete({
        source: "getUsers.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 for user ID -->  
<input type="hidden" id="userID" name="userID" value=""/>

SEE ALSO: Add WYSIWYG HTML Editor to Textarea with CKEditor

Database Configuration (dbConfig.php)

You can use the dbConfig.php file 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     = "allsweb";

// 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 getUsers.php is loaded by the autocomplete() method of jQuery UI Autocomplete plugin.

<?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 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"/>
            <span>'.$name.'</span>
        </a>';
        array_push($userData, $data);
    }
}

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

SEE ALSO: Auto Resize Textarea Height using jQuery

Conclusion

Firstly, if you want to integrate the member’s search feature, this jQuery Autocomplete textbox with images is beneficial to create the search input user-friendly. Secondly, the sample code explains you to add images, text, and custom HTML in the autocomplete widget. At last, you can increase this script to customize the autocomplete dropdown and render HTML elements.

Also, read our previous blog- Create Short URL using PHP URL Shortener

Exit mobile version