Autocomplete textbox
feature shows the suggestion list when the user enters a value. The suggestions are, in a way, related to the entered keyword.
For example, when typing in a Google search box, it displays auto-suggested keywords in a dropdown.
This tutorial will show how to add this feature to a website. The code uses the JQuery library with PHP and MySQL to show dynamic auto-suggestions on entering the search key.
It allows typing the start letter of the country name to get suggested with the list of country names accordingly. See the linked code for enabling autocomplete using the jQuery-Ui library.
The specialty of this example is that it also allows adding a new option that is not present in the list of suggestions.
On key-up, a function executes the Jquery Autocomplete script. It reads suggestions based on entered value. This event handler is an AJAX function. It requests PHP for the list of related countries from the database.
When submitting a new country, the PHP will update the database. Then, this new option will come from the next time onwards.
This HTML is for creating an autocomplete search field in a form. It is a suggestion box that displays dynamic auto-suggestions via AJAX.
On the key-up event of this input field, the AJAX script sends the request to the PHP. The PHP search performs database fetch about the entered keyword.
This HTML form also posts data not chosen from the suggestions. This feature allows adding new options to the source of the search suggestions.
index.php
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div class="outer-container">
<div class="row">
<form id="addCountryForm" autocomplete="off" method="post">
<div Class="input-row">
<label for="countryName">Country Name:</label><input type="text"
id="countryName" name="countryName" required>
<div id="countryList"></div>
</div>
<input type="submit" class="submit-btn" value="Save Country">
<div id="message"></div>
</form>
</div>
</div>
</body>
</html>
This code uses AJAX to show the dynamic autocomplete dropdown. This script sends the user input to the PHP endpoint.
In the success callback, the AJAX script captures the response and updates the auto-suggestions in the UI. This happens on the key-up event.
The suggested options are selectable. The input box will be filled with the chosen option on clicking each option.
Then, the form input is posted to the PHP via AJAX on the form-submit event.
This jQuery script shows the fade-in fade-out effect to display and hide the autocomplete dropdown in the UI.
index.php(ajax script)
$(document).ready(function() {
$('#countryName').keyup(function() {
var query = $(this).val();
if (query != '') {
$.ajax({
url: 'searchCountry.php',
type: 'POST',
data: {
query: query
},
success: function(response) {
$('#countryList').fadeIn();
$('#countryList').html(response);
}
});
} else {
$('#countryList').fadeOut();
$('#countryList').html('');
}
});
$(document).on('click', 'li', function() {
$('#countryName').val($(this).text());
$('#countryList').fadeOut();
});
$('#addCountryForm').submit(function(event) {
event.preventDefault();
var countryName = $('#countryName').val();
$.ajax({
type: 'POST',
url: 'addCountry.php',
data: {
countryName: countryName
},
success: function(response) {
$('#countryList').hide();
$('#message').html(response).show();
}
});
});
});
Import this SQL to create to database structure to save the autocomplete suggestions. It has some initial data that helps to understand the autocomplete code during the execution.
database.sql
CREATE TABLE IF NOT EXISTS `democountries` (
`id` int NOT NULL AUTO_INCREMENT,
`countryname` varchar(255) NOT NULL,
PRIMARY KEY (id)
);
INSERT INTO `democountries` (`countryname`) VALUES
('Afghanistan'),
('Albania'),
('Bahamas'),
('Bahrain'),
('Cambodia'),
('Cameroon'),
('Denmark'),
('Djibouti'),
('East Timor'),
('Ecuador'),
('Falkland Islands (Malvinas)'),
('Faroe Islands'),
('Gabon'),
('Gambia'),
('Haiti'),
('Heard and Mc Donald Islands'),
('Iceland'),
('India'),
('Jamaica'),
('Japan'),
('Kenya'),
('Kiribati'),
('Lao Peoples Democratic Republic'),
('Latvia'),
('Macau'),
('Macedonia');
The PHP code prepares the MySQL select query to fetch suggestions based on the search keyword.
It fetches records by searching for the country names that start with the keyword sent via AJAX.
This endpoint builds the HTML lists of autocomplete suggestions. This HTML response is used to update the UI to render relevant suggestions.
searchCountry.php
<?php
$conn = new mysqli('localhost', 'root', '', 'db_autocomplete');
if (isset($_POST['query'])) {
$query = "{$_POST['query']}%";
$stmt = $conn->prepare("SELECT countryname FROM democountries WHERE countryname LIKE ? ORDER BY countryname ASC");
$stmt->bind_param("s", $query);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo '<li>' . $row['countryname'] . '</li>';
}
}
}
?>
The expected value is not in the database if no result is found for the entered keyword. This code allows you to update the existing source with your new option.
The form submits action calls the below PHP script. It checks if the country name sent by the AJAX form submit is existed in the database. If not, it inserts that new country name.
After this insert, the newly added item can be seen in the suggestion box in the subsequent autocomplete search.
addCountry.php
<?php
$conn = new mysqli('localhost', 'root', '', 'db_autocomplete');
if (isset($_POST['countryName'])) {
$countryName = "{$_POST['countryName']}";
$stmt = $conn->prepare("SELECT * FROM democountries WHERE countryname =?");
$stmt->bind_param("s", $countryName);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
echo '<p>Country Selected: ' . $countryName . '</p>';
} else {
$stmt = $conn->prepare("INSERT INTO democountries (countryname) VALUES (?)");
$stmt->bind_param("s", $countryName);
$stmt->execute();
$result = $stmt->insert_id;
if (! empty($result)) {
echo $countryName . ' saved to the country database.</br>';
} else {
echo '<p>Error adding ' . $countryName . ' to the database: ' . mysqli_error($conn) . '</p>';
}
}
}
?>
In this script, I give a custom autocomplete solution. But, many libraries are available to provide advanced feature-packed autocomplete util for your application.
These libraries give additional features associated with the autocomplete solution.
Most of us experience the advantages of the autocomplete feature. But, this list is to mention the pros of this must-needed UI feature intensely.
THANKS VINCY!!!!
Welcome Jonathan!!