Autocomplete with thousands entries
I All, I'm trying to use the UI autocomplete toghether with a php page that retreives thousands of entries from a Mysql database (about 20.000).
My problem: when I write something in the input field, I often obtain a script timeout and the autocomplete doesn't work.
Has anybody a working example with mysql to post here?
Thank you
Here the code I'm using:
In the page with the form:
- <link type="text/css" rel="stylesheet" media="all" href="jquery/css/ui-lightness/jquery-ui-1.8.10.custom.css" />
- <script type="text/javascript" src="jquery/js/jquery-1.4.4.min.js"></script>
- <script type="text/javascript" src="jquery/js/jquery-ui-1.8.10.custom.min.js"></script>
- <script>
- $(function() {
- var cache = {},
- lastXhr;
- $( "#birds" ).autocomplete({
- minLength: 2,
- source: function( request, response ) {
- var term = request.term;
- if ( term in cache ) {
- response( cache[ term ] );
- return;
- }
- lastXhr = $.getJSON( "jquery/search.php", request, function( data, status, xhr ) {
- cache[ term ] = data;
- if ( xhr === lastXhr ) {
- response( data );
- }
- });
- }
- });
- });
- </script>
- <br /><br />
- <div class="demo">
- <div class="ui-widget">
- <label for="birds">Birds: </label>
- <input id="birds" />
- </div>
- <div class="ui-widget" style="margin-top:2em; font-family:Arial">
- Result:
- <div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
- </div>
- </div>
In the search.php page:
- $dbuser="test";
- $dbpass="test";
- $dbname="test_db";
- $chandle = mysql_connect("localhost", $dbuser, $dbpass)
- or die("Connection Failure to Database");
- mysql_select_db($dbname, $chandle) or die ($dbname . " Database not found. " . $dbuser);
-
- $return_arr = array();
- $query = "
- SELECT id, name
- FROM
- names
- ";
- $dbresult = mysql_db_query($dbname, $query) or die("Failed Query of " . $query);
- while ($row = mysql_fetch_array($dbresult, MYSQL_ASSOC)) {
- $row_array['id'] = $row['name'];
- array_push($return_arr,$row_array);
- }
- mysql_close($chandle);
- echo json_encode($return_arr);