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.

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 DemoDownload

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.

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

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 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
require_once("dbcontroller.php");
$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">
<?php
foreach($result as $country) {
?>
<li onClick="selectCountry('<?php echo $country["country_name"]; ?>');"><?php echo $country["country_name"]; ?></li>
<?php } ?>
</ul>
<?php } } ?>

View DemoDownload

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

↑ Back to Top