I’m developing a social networking website, and improving the front-end with some spit and polish.
One of the improvements I’m implementing is an AJAX validator for chat names. The set-up is this:
Visitor heads to registration page and the visitor types their desired chat name into a field. Whilst typing, the user is given instant feedback as to whether that chat name is already in use, contains illegal characters, is the wrong length etc.
I’ve got this working: I’ve set up a simple PHP script to act as an AJAX handler that’s bound to my input’s onkeyup and blur events. However, each request involves a database query which can’t be good.
My question is: how can I streamline this? Surely a database query upon each onkeyup or blur is not a good idea?
I recommend the following (time-based) strategy:
This way you can do a request everytime the user stops typing for at least 500 – 1000 ms. This saves you some requests while the user is still typing. You can start the request immediately when the blur-event is fired, since the user is not typing any more, obviously.
Example (using jQuery) with 500 ms:
As others stated, checking for invalid characters, etc. should be done client-side as well as server-side, since you cannot trust the client.