Jquery Ajax on KeyDown that checks for username avail. Too many DB hits?
If I have a function that checks the database to see if a username is available and I do an Ajax call to that function on the jquery keydown event, is that too many database hits? Every time the user hits a key the call will me made. Is t开发者_StackOverflow社区here a better approach?
Thanks
Alternatively, why not call the check onBlur?
Then the user would only check for availability when they click onto the next field.
I usually find this implemented in the following ways across various sites.
- Handle onchange event of the username/email textbox and do the validation in the onchange event.
- Have a button/image next to the username/email textbox with label "Check availability" and the do the validation if the user clicks on the image/button.
In either case, it's always advised to perform a server side check and then display the errors (if any) as a response.
Use a setTimeOut()
to run it 1 second after the last keydown. If the user types fast enough, it will result in only one query. If your database indexes are properly set up, even a large amount of queries shouldn't be a problem.
In the past I've used the jQuery Autocomplete Control. It will do the request a few seconds after the user is done typing, preventing a ridiciulous amount of requests going to the server.
I'm using setTimeout()
var timer;
$('#name').keyup(function(){
clearTimeout(timer);
timer = setTimeout(name_check, 300);
});
精彩评论