I want to build a jquery Auto Complete input field for the city the user stays in. When the user starts typing in the words i wanna display a list of 5 cities with the closest associations in this format [City, Country]
i have three tables
- Country (id, country_name)
- Region (id, region_name, country_id)
- City (id, city_name, region_id, country_id)
when a user selects a city i want to capture the id of the City to insert it into the database.
How should i do this with Autocomplete ?
Should i set a hidden field with the id of the city or pass the name of the City and then check whats its id doing a select ? Problem here is there are cities across the globe with the same name and it will get diff to identify it.
JS code
$("#UserCity").autocomplete({
source: function (request, response) {
$.ajax({
url: "http://localhost/baku/users/location/",
dataType: "json",
data: {
data: request.term
},
success: function (data) {
/// Need to modify this part
response($.map(data.geonames, function (item) {
return {
label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
value: item.name
}
}));
}
});
},
minLength: 2
});
Example JSON String i get from Ajax
[{"name":"Banaras, Uttar Pradesh, India","city_id":"1927","region_id":"2193","country_id":"113"},{"name":"Banda, Uttar Pradesh, India","city_id":"1938","region_id":"2193","country_id":"113"},{"name":"Bangalore, Karnataka, India","city_id":"1949","region_id":"2185","country_id":"113"},{"name":"Banganapalle, Andhra Pradesh, India","city_id":"1950","region_id":"2169","country_id":"113"},{"name":"Banswara, Rajasthan, India","city_id":"1983","region_id":"2190","country_id":"113"},{"name":"Banur, Punjab, India","city_id":"1987","region_id":"2189","country_id":"113"}]
I wanna Display name as the list and take City_id as the passable parameter via the Form so that i dont need to again do a database query.
the Array
Array
(
[0] => Array
(
[name] => Banaras, Uttar Pradesh, India
[city_id] => 1927
[region_id] => 2193
[country_id] => 113
)
[1] => Array
(
[name] => Banda, Uttar Pradesh, India
[city_id] => 1938
[region_id] => 2193
[country_id] => 113
)
[2] => Array
(
[name] => Bangalore, Karnataka, India
[city_id] => 1949
[region_id] => 2185
[country_id] => 113
)
[3] => Array
(
[name] => Banganapalle, Andhra Pradesh, India
[city_id] => 1950
[region_id] => 2169
[country_id] => 113
)
[4] => Array
(
[name] => Banswara, Rajasthan, India
[city_id] => 1983
[region_id] => 2190
[country_id] => 113
)
[5] => Array
(
[name] => Banur, Punjab, India
[city_id] => 1987
[region_id] => 2189
[country_id] => 113
)
)
HTML:
JQuery:
PHP: