Picking a username is something that a huge number of signup forms require you to do, and it must be a unique username, which means if you use anything remotely common, you'll have to reload the page and things like password fields will need to be filled in again.
I'm just going to quickly run through how you can check this on the fly using
prototype (a very good OOP based javascript library). Cutting straight to the working example - view the complete test page
here.
The html:The html is very straight forward, we just have a simple form, with the addition of a button which calls the checkUsername() function, and an empty div (checkResult) to hold the response from the server.
Prototype is a large javascript library, and probably overkill for a simple task such as this, however if you're implementing other functions and utilising javascript a lot on your site, it becomes worth while. The prototype library is included in the page, and allows us to easily code a reliable js function to do what we need.
The javascript:Ok, so with our basic html setup, we'll write our javascript function.
function checkUsername(){ var username = $F('username'); new Ajax.Updater('checkResult', 'result.php?username=' + username, {asynchronous:true});}Easy no? To explain, prototype provides us with some nice shortcut functions, the $F function will return the value of of a form field. Your form field must have an ID (rather than referring to it by name).
Our function then creates a new Ajax Updater, and the AJAX is handled in the background. CheckResult is the ID of the <DIV> element we want the results to be placed in. The next argument simply tells the Updater to get its results from result.php, and pass along our username variable.
The PHP:Our php script is very simple, it checks the $_GET['username'] variable passed to it, and echo's a result depending on whether the name is valid or not, this output is returned and placed in the CheckResult div we mentioned earlier.
And that's it! You should probably add some more checks, and some more descriptive error messages, but the basics are there. Also don't forget people who don't have javascript turned on, so you might want to display the checking button only when javascript is enabled.
Download a .zip of the files used here, and upload to your PHP enabled web server.