jQuery Autocomplete Ajax
jQuery Autocomplete Ajax feature provides an instant action of suggestion when user start typing the name. It provides a quick search to users and selects fast their option from the populated list from the dropdown list.
When the user starts typing the autocomplete plugin fetch the data from the database which are matched to your keywords and listed to your textbox which you type. You can integrate jQuery UI Autocomplete easily to your project.
Generally, the autocomplete feature fetch the data as text under your textbox from the database. But you can customize the autocomplete data using custom HTML. When you want to show the design layout premium of your web page, you need this feature.
We will show you how to add custom HTML and show images and text in jQuery autocomplete feature using jQuery, PHP and MySQL.
In this example, we integrate the autocomplete feature with text and image shows under your textbox or autocomplete dropdown.
- Autocomplete text box fetch user by name.
- When a user starts typing in the text box, matched users are fetched from the database.
- The user’s data coming with name and image on the auto-suggestion.
Also Read:
Codeigniter send email to multiple recipients using Smarty Template Engine and JQuery
Create a Database Table
To store auto-suggestion data needs a table on the database, here is the code snippet copy the code and make a database, paste the query on SQL tab, click on GO.
1 2 3 4 5 6 7 8 9 10 |
CREATE TABLE `user_details` ( `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 Text box Feature
Include below files which help on autocomplete feature. Get jQuery new version CDN jQuery CDN
1 2 3 4 5 6 7 8 |
<!-- jQuery library --> <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script> <!-- jQueryUI library --> <link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css"> <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.js"></script> |
Using autocomplete() to use the feature of jQuery UI Autocomplete.
- source – On the source, we specify the path of the file which fetches the data from the database.
- minLength – On minLength, the user must type a minimum number of words to start searching.
- select – This is an event, on this event when data fetched on auto-suggestion user selects that user, the user name sets on the textbox and their id set to a hidden field.
- _renderItem- This helps to customise the HTML and fetch the text with an image.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
$(document).ready(function(){ $("#SearchName").autocomplete({ source: "getUsers.php", minLength: 1, select: function(event, ui) { $("#SearchName").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 ); }; }); |
HTML Snippet
On HTML input field we attach the autocomplete feature,
When the user starts typing, the suggestions are retrieved from the database and show under the textbox.
After that when you select any of from the suggestion that set to on the textbox and their id set on the hidden field.
1 2 3 4 5 6 7 |
<!-- Autocomplete input field --> <input id="SearchName" placeholder="Enter member name..." autocomplete="off"> <!-- Hidden input for user ID --> <input type="hidden" id="userID" name="userID" value=""/> |
jQuery Autocomplete Feature Snippet and Database Configuartion (getUserdetails.php)
The database configuration for connect to specific database, here specify the host, database user, password and database name.
1 2 3 4 |
// Database configuration $con = mysqli_connect("localhost","root","password","dbname"); |
- The getUserdetails.php file loaded the Autocomplete Jquery UI feature
- The autocomplete() function makes GET request to source URL and set the parameter to query string.
- Use $_GET[”] method to get the term which user inputs.
- Write the query for fetch match data from database using PHP and MySQL.
- Fetch the user name, image and filter array generated data.
- Render the filtered data in JSON format.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<?php // Database configuration $con = mysqli_connect("localhost","DBUSERNAME","DBPASSWORD","DBNAME"); // Get search term $searchTerm = $_GET['term']; // Get matched data from the database $query = "SELECT id, first_name, last_name, image FROM user_details WHERE (first_name LIKE '%".$searchTerm."%' OR last_name LIKE '%".$searchTerm."%') AND status = '1' ORDER BY first_name ASC"; $result = mysqli_query($con,$query); // Generate users data array $userData = array(); if($result->num_rows > 0){ while($row = mysqli_fetch_assoc($result)){ $name = $row['first_name'].' '.$row['last_name']; $data['id'] = $row['id']; $data['value'] = $name; $data['label'] = ' <a href="javascript:void(0);"> <img src="'.$row['image'].'" width="50" height="50"/> <span>'.$name.'</span> </a>'; array_push($userData, $data); } } // Return results as json encoded array echo json_encode($userData); ?> |
Conclusion
If you want to integrate the feature of autocomplete with text and image data on your project or website, it is very helpful to integrate custom HTML data. And also you can extend the feature as you want.
Also Check:
- How JavaScript For Loop Works (Complete Guide With Example)
- Create Repository & Push Code To GitHub First Time
- Migrate WordPress Site To New Host Manually
- Set-up Firebase Project using Firebase Console
Happy Coding..!
[…] jQuery autocomplete ajax with Text and Image […]
[…] jQuery autocomplete ajax with Text and Image […]
[…] jQuery autocomplete ajax with Text and Image […]