Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery UI - speeding up Autocomplete

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.

like image 229
TerryMatula Avatar asked Oct 11 '22 04:10

TerryMatula


1 Answers

  1. Autocomplete assumes that if you return it, it's a valid answer. So: no.

  2. Yes, pulling from a flat file would be a lot faster than hitting your db for every key stroke. However, if you threw some caching (memcache) in front of the db, it would probably be just as fast as a flat file.

But really, because you're (likely) searching a (relatively) small set for your term, it's going to be really fast anyway.

From a scaling perspective, stick them in a flat file or use caching.

As a side note: look into mysql_escape_string() for using $country and $term. Otherwise you're open to SQL Injection attacks.

like image 197
helloandre Avatar answered Nov 02 '22 07:11

helloandre