jQuery AJAX AutoComplete with Create-New Feature

by Vincy. Last modified on February 24th, 2024.

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.

View Demo

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.

jquery ajax autocomplete create new

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.

Steps to have a autocomplete field with a create-new option

  1. Create HTML with a autocomplete field.
  2. Integrate jQuery library and initialize autocomplete for the field.
  3. Create an external data source (database here) for displaying suggestions.
  4. Fetch the autocomplete suggestions from the database using PHP.
  5. Insert a newly created option into the database.

1. Create HTML with a autocomplete field

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>

2. Integrate the jQuery library and initialize autocomplete for the field

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

3. Create an external data source (database here) for displaying suggestions

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

4. Fetch the autocomplete suggestions from the database using PHP

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>';
        }
    }
}
?>

5. Insert a newly created option into the database

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>';
        }
    }
}
?>

Different libraries providing Autocomplete feature

In this script, I give a custom autocomplete solution. But, many libraries are available to provide advanced feature-packed autocomplete util for your application.

  1. The jQueryUI provides autocomplete feature to enable an HTML field.
  2. One more library is the jQuery Autocompleter plugin that captures more data from the options to be chosen.

These libraries give additional features associated with the autocomplete solution.

  1. It allows to select single and multiple values from the autocomplete dropdown.
  2. It reads the option index or the key-value pair of the chosen item from the list.

Advantages of autocomplete

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.

  1. It’s one of the top time-saving UI utilities that saves users the effort of typing the full option.
  2. It’s easy to search and get your results by shortlisting and narrowing. This is the same as how a search feature of a data table narrows down the result set.
  3. It helps to get relevant searches.

View Demo Download

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Comments to “jQuery AJAX AutoComplete with Create-New Feature”

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page