jQuery AJAX Autocomplete – Country Example

by Vincy. Last modified on September 5th, 2022.

Autocomplete feature is used to provide the auto suggestion for users while entering input. In this tutorial, we are going to suggest country names for the users based on the keyword they entered into the input field by using jQuery AJAX.

jQuery Autocomplete function is called on the key-up event of the input field. This function requests PHP for the list of countries via AJAX by sending the value of the input field. In PHP, it reads country names from the database that starts with the keyword entered by the user.

View Demo

Input Field with Autocomplete Feature

In the following code, the HTML has a search input and a suggestion box to display AJAX autocomplete results. On the key-up event of the search input field, it calls jQuery function to auto-suggest countries to the user.

<html>
<head>
<title>jQuery AJAX Autocomplete - Country Example</title>
</head>
<body>
    <h1>jQuery AJAX Autocomplete - Country Example</h1>
    <div class="frmSearch">
        <input type="text" id="search-box" placeholder="Country Name" />
        <div id="suggesstion-box"></div>
    </div>
</body>
</html>

jQuery Autocomplete Script

The following jQuery script uses AJAX to send user input to a PHP page to fetch auto-complete suggestion. On success, the list of countries will be shown to the user. On clicking the list of suggested item, then the value is added to the input box.

// AJAX call for autocomplete 
$(document).ready(function() {
	$("#search-box").keyup(function() {
		$.ajax({
			type: "POST",
			url: "readCountry.php",
			data: 'keyword=' + $(this).val(),
			beforeSend: function() {
				$("#search-box").css("background", "#FFF url(LoaderIcon.gif) no-repeat 165px");
			},
			success: function(data) {
				$("#suggesstion-box").show();
				$("#suggesstion-box").html(data);
				$("#search-box").css("background", "#FFF");
			}
		});
	});
});
//To select a country name
function selectCountry(val) {
	$("#search-box").val(val);
	$("#suggesstion-box").hide();
}

Reading Country Names from Database using PHP

In PHP code, it fetches data from the country table where the country name starts with the keyword passed by the AJAX request. After getting the results from the database, it iterates the resultant array and forms auto-complete suggestion list.

<?php
$conn = new mysqli('localhost', 'root', '', 'phppot_examples');
if (! empty($_POST["keyword"])) {
    $sql = $conn->prepare("SELECT * FROM country WHERE country_name LIKE  ? ORDER BY country_name LIMIT 0,6");
    $search = "{$_POST['keyword']}%";
    $sql->bind_param("s", $search);
    $sql->execute();
    $result = $sql->get_result();
    if (! empty($result)) {
        ?>
<ul id="country-list">
<?php
        foreach ($result as $country) {
            ?>
   <li
        onClick="selectCountry('<?php echo $country["country_name"]; ?>');">
      <?php echo $country["country_name"]; ?>
    </li>
<?php
        } // end for
        ?>
</ul>
<?php
    } // end if not empty
}
?>

Database script

Import this SQL to get the result of the autocomplete from the database on-key-press.

CREATE TABLE IF NOT EXISTS `country` (
`id` int(11) NOT NULL,
  `country_name` varchar(255) NOT NULL
);

INSERT INTO `country` (`id`, `country_name`) VALUES
(1, 'Afghanistan'),
(2, 'Albania'),
(3, 'Bahamas'),
(4, 'Bahrain'),
(5, 'Cambodia'),
(6, 'Cameroon'),
(7, 'Denmark'),
(8, 'Djibouti'),
(9, 'East Timor'),
(10, 'Ecuador'),
(11, 'Falkland Islands (Malvinas)'),
(12, 'Faroe Islands'),
(13, 'Gabon'),
(14, 'Gambia'),
(15, 'Haiti'),
(16, 'Heard and Mc Donald Islands'),
(17, 'Iceland'),
(18, 'India'),
(19, 'Jamaica'),
(20, 'Japan'),
(21, 'Kenya'),
(22, 'Kiribati'),
(23, 'Lao Peoples Democratic Republic'),
(24, 'Latvia'),
(25, 'Macau'),
(26, 'Macedonia'),
(27, 'Namibia'),
(28, 'Nauru'),
(29, 'Oman'),
(30, 'Pakistan'),
(31, 'Palau'),
(32, 'Qatar'),
(33, 'Reunion'),
(34, 'Romania'),
(35, 'Saint Kitts and Nevis'),
(36, 'Saint Lucia'),
(37, 'Taiwan'),
(38, 'Tajikistan'),
(39, 'Uganda'),
(40, 'Ukraine'),
(41, 'Vanuatu'),
(42, 'Vatican City State'),
(43, 'Wallis and Futuna Islands'),
(44, 'Western Sahara'),
(45, 'Yemen'),
(46, 'Yugoslavia'),
(47, 'Zaire'),
(48, 'Zambia');

View DemoDownload

↑ Back to Top

Share this page