user3748173
user3748173

Reputation: 215

jQuery autocomplete too many db requests

How to solve problem of too many requests to a database when using db data in jQuery ajax autocomplete widget? Basically every time the user inserts a letter, the script makes a ajax request to a database, what are the best practises to keep db requests to minimal?

I get the data from third party app so i have to consider that it can change in my application.

Upvotes: 2

Views: 3278

Answers (3)

West
West

Reputation: 91

As @Remq say, you can try this

  $("your_selector").autocomplete({
     source: debounce(querySourceData, 1000),
  });

  function debounce(fn, delay) {
    var timer;
    return function() {
      var args = [].slice.call(arguments);
      var context = this;
      if (timer) {
        window.clearTimeout(timer);
      }
      timer = window.setTimeout(function() {
        fn.apply(context, args);
      }, delay);
    };
  };

  function querySourceData(request, response) {
     $.ajax({
        url: '/your_api',
        success: function(data = []) {
           response(data);
        },
        error: function() {
           response([]);
        }
     });
  }

Upvotes: 2

Aethyn
Aethyn

Reputation: 705

I had the same problem few months ago.
I found two solutions :

Solution 1 :
Don't start the query from the first letter typed. Use the "minLength" Autocomplete attribute. minLength documentation here. With that attribute added, the first query will start at n where n is the number (integer) of letter previously typed.
Example :

$( ".selector" ).autocomplete({
    minLength: 3
});

Solution 2 :
Add a (very short but nice for the database) delay between multiples send. A short one like 250/300/500ms (depending of which ping you have between you and the database, or users bandwidth) is really appreciable. Delay documentation link here. Value is in milliseconds (integer).
Example :

$( ".selector" ).autocomplete({
    delay: 500
});

I hope it will match to your needs.
Don't hesitate to use both of two.

Upvotes: 9

Remq
Remq

Reputation: 428

You can throttle or debounce the requests. These functions are often included in libraries like Lodash (https://lodash.com/docs/4.17.2#debounce).

Debounce: When a key is pressed, a timer starts. When the timer ends you make the Ajax call. When during the timer another key is pressed, the timer gets reset.

Throttle: When a key is pressed, a Ajax call is made and a timer starts. When another key is pressed while the timer is running, it is ignored.

Upvotes: 5

Related Questions