How to solve problem of too many requests to a database when using db data in jQuery ajax autoplete 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.
How to solve problem of too many requests to a database when using db data in jQuery ajax autoplete 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.
Share Improve this question asked Dec 27, 2016 at 14:46 user3748173user3748173 2152 silver badges10 bronze badges 2- 2 you can use minLength property of jquery autoplate. – Mehmet Commented Dec 27, 2016 at 14:49
- Why not try Scrollable? look example: anseki.github.io/jquery-ui-autoplete-scroll – KingRider Commented Dec 27, 2016 at 16:46
3 Answers
Reset to default 9I 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" Autoplete 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" ).autoplete({
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" ).autoplete({
delay: 500
});
I hope it will match to your needs.
Don't hesitate to use both of two.
You can throttle or debounce the requests. These functions are often included in libraries like Lodash (https://lodash./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.
As @Remq say, you can try this
$("your_selector").autoplete({
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([]);
}
});
}