Using Ajax to Validate Forms
Posted on 18th December 2007 — Forms are such a common element on the Internet we tend to blunder through them without too much thought. However, if the web site has added a few nice touches that make the process easier, it tends to speed up the process and reduce any frustration in finding our preferred username (i.e. try getting your name under Hotmail!).

There’s two types of validation:
What can we do?
So why do it?
Examples in the wild
Howto
As with all these tutorials, I expect that you have built your solution to the point where it works, but now we want to add our splash of JavaScript magic.
In our baseline example, my requirements are:
Username validation
Our PHP function to validate the username reads:
This format for a response is good, because we are using it to display error messages on the page, but we can also convert it to JSON and use it in our Ajax response later on.
Markup
Again, it’s assumed your markup is already designed to show error messages.
For this example the following markup is being used within a
fieldset:jQuery
Our client side check will perform the following:
The code breaks down as follows:
Run the JavaScript in this (anonymous) function when the document has loaded.
Create a cached copy of the
validateUsernamespan because it will help a little with optimisation (it’s a good practise to have).Run the JavaScript in this (anonymous) function on key up.
Cache the ‘this’ instance as we need access to it within a setTimeout, where ‘this’ is set to ‘window’, which can cause all manners of confusion.
Only run the check if the username has actually changed – also means we skip meta keys.
The timeout logic means the ajax doesn’t fire with every key press, i.e. if the user holds down a particular key, it will only fire when the release the key.
Show our holding text in the validation message space.
Fire an ajax request in 1/5 of a second.
The actual Ajax request. If the script
ajax-validation.phpreturns any response, convert it to JSON and put the ‘msg’ field in to the validation message.The fields are set in the PHP server response. You can see this working in the demo, and view the source, in particular look at the $resp array from check_username.
Finally, put the current value in to a cache, to make sure we ignore meta keys (from above).
Server response
Now all I have to add to the PHP code, that already handles normal username validation is:
So long as this is high enough in the logic, it will just check the username is valid, using our existing function and convert the response to a JSON object (you may need to add JSON support for PHP, otherwise it’s bundled with PHP 5.2.0).
Example & taking it further
In the example I’ve provided, I’ve also shown how we can add JavaScript to a normally coded page to also validate the user providing an avatar URL.
You should follow me on Twitter here I tweet about jQuery amongst the usual tweet-splurges!