jquery ajax example,jQuery AJAX Autocomplete – Country Example

jQuery AJAX Autocomplete – Country Example

by Vincy. Last modified on June 1st, 2021.

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.

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.

b9b19f3ed1813b450bdbb5709d50155a.png

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.

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)) {

?>

foreach($result as $country) {

?>

');"><?php echo $country["country_name"]; ?>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值