jQuery AJAX Autocomplete – Country Example

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.

We have jQuery script to call AJAX request on the key-up event. This request will read country names from the database that starts with the keyword entered by the user.


View DemoDownload

Input Field with Autocomplete Feature

This HTML code contains text input field for auto suggesting a country name to the user. On key-up from this input field, the jQuery function is triggered.

<div class="frmSearch">
	<input type="text" id="search-box" placeholder="Country Name" />
	<div id="suggesstion-box"></div>

jQuery Autocomplete Script

This script sends user input to a PHP page via jQuery AJAX function. On success, the list of countries will be shown to the user. We can select a country name for the input field from the auto-suggested list.

// AJAX call for autocomplete 
		type: "POST",
		url: "readCountry.php",
		beforeSend: function(){
			$("#search-box").css("background","#FFF url(LoaderIcon.gif) no-repeat 165px");
		success: function(data){
//To select country name
function selectCountry(val) {

Reading Country Names from Database using PHP

This PHP script fetches data from the country table and forms HTML to be returned as auto-suggestion.

$db_handle = new DBController();
if(!empty($_POST["keyword"])) {
$query ="SELECT * FROM country WHERE country_name like '" . $_POST["keyword"] . "%' ORDER BY country_name LIMIT 0,6";
$result = $db_handle->runQuery($query);
if(!empty($result)) {
<ul id="country-list">
foreach($result as $country) {
<li onClick="selectCountry('<?php echo $country["country_name"]; ?>');"><?php echo $country["country_name"]; ?></li>
<?php } ?>
<?php } } ?>

View DemoDownload

This jQuery code tutorial was published on November 6, 2014.

↑ Back to Top