I've got autocomplete working fine, but I'm trying to figure out way to make it faster. Here's my HTML:
Country: <select name='country' id='country' onchange="renewAutocomplete();">
<option value='US'>USA</option>
<option value='UK'>United Kingdom</option>
</select><br/>
City: <input type='text' name='city' id='city' />
<script>
function renewAutocomplete() {
$( "#city" ).autocomplete({
source: "searchCities/" + $('#country').val(),
minLength: 2
});
}
</script>
The PHP/mySQL query is pretty basic:
$term = $_GET['term'];
$sql = "SELECT city FROM cities WHERE country_code = '{$country}' AND city LIKE '{$term}%'";
OF course, this means a new query for every keystroke. It helps a bit to add some caching, but it still isn't as fast as I think it should be.
Question 1 My first thought was to get ALL the cities in one db call when the Country is selected. Is there a way to assign the returned JSON of all the cities of country into a variable that autocomplete can use? My initial tests would just popup all the cities as you typed:
$.get("searchCities/" + $('#country').val(), function(data) {
$( "#city" ).autocomplete({
source: data,
minLength: 2
});
});
PHP:
$sql = "SELECT city FROM cities WHERE country_code = '{$country}'";
Question 2 Since cities and countries don't change a lot (usually), would it be faster to just have a flat file with all the values?
Or is there any other way to make a faster autocomplete?
Thanks.