Jquery Mobile Auto complete sending multiple requests
I have jquery mobile autocomplete which is functional, but if I type anything it sends requests thrice for one keyword. How can I avoid this? I am sending country and city name along with the keyword to get City name and City code. Upon city name selection city code gets populated on a different input box. I would really appreciate any suggestion. Thanks.
- //Auto Complete Function
$( "#cityname" ).keyup(function() {
var country_val=$('#country').val();
var state_val=$('#state').val();
//City Name Autocomplete
$(document).on("click", "#cityname-autocomplete li", function () {
var text = $(this).text();
$(this).closest("ul").prev("form").find("input").val(text);
$(this).closest('[data-role=listview]').children().addClass('ui-screen-hidden');
});
$( "#cityname-autocomplete" ).on( "filterablebeforefilter", function ( e, data ) {
var $ul = $( this ),
$input = $( data.input ),
value = $input.val(),
html = "";
$ul.html( "" );
if ( value && value.length > 2 ) {
$ul.html( "<li><div class='ui-loader'><span class='ui-icon ui-icon-loading'></span></div></li>" );
$ul.listview( "refresh" );
$.ajax({
type: "POST",
url:"autocomplete.php",
data: {country:country_val,state:state_val,term:$input.val()},
dataType: "json"
})
.then( function ( response ) {
$.each( response, function ( i, val ) {
html += "<li>" + val['value'] +":"+val['citycode']+ "</li>";
});
$ul.html( html );
$ul.listview( "refresh" );
$ul.trigger( "updatelayout");
$("#cityname-autocomplete").on("click", "li", function () {
var text = $(this).text();
var text = $(this).text();
var values= text.split(':');
var citynameInput=values[0];
var cityCodeInput=values[1];
$("#cityname").val(citynameInput);
$("#citycode").val(cityCodeInput);
$(this).siblings().addBack().addClass("ui-screen-hidden");
});
});
}
});
});