JQuery UI - Autocomplete Acceleration

My autocomplete works fine, but I'm trying to figure out a way to speed things up. Here is 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 simple:

$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. This helps add a bit of caching, but it's still not as fast as I think it should be.

Question 1 My first thought was to get ALL cities in one db call when the Country is selected. Is there a way to assign the returned JSON of all cities in a country to a variable that autocomplete can use? My initial tests will simply display all cities as I type:

      $.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 do not change much (usually), would it be faster to just have a flat file with all the values?

?

.

+4
1
  • Autocomplete , , , . : .

  • , , . , (memcache) db, , , , .

, () () , .

.

: mysql_escape_string() $country $term. SQL Injection.

+3

All Articles