I have created this simple registration form which makes user registration using asynchronous requests in the background, checking if a duplicate username or email exists, and presenting the user with status of registration on the same page without have to reload the page even once.

It is simple, but with some prerequisites for my particular example. They are
  1. MySQL database for saving registrations
  2. PHP registration page for connecting to database
  3. Some basic javascript knowledge
 So having set up the above stuff, we shall get started. If you don't want to code all yourself, use my code from Github.

First of all, create for yourself a nice form. It doesn't take much right? Just make sure you attach an 'id' attribute to each input field for convenience later. Here is my version.

If you see, after the form I have left an empty div. It is for displaying the response we get from our ajax request. You can, of course, add nice styling to this div. Having our form set, we can concentrate on the jQuery part.

Start with making sure our DOM is loaded with $(document).ready() function. Grab hold of the click event of the form submit button. Then we get the values in the username, email and password fields.

Here, we can have some basic checks to make sure form is filled up. We could have used the required attribute to make sure all fields are filled, but that does not give us full control, so use Javascript or jQuery and display some custom messages. I clubbed them together in a single if.

Next, using the simple $.ajax() function, make a request and get the response code. My action page is register.php, and I have make simple error codes to detect what response the backend gave. Here are the codes, for some reference.

// Code returns 101 for "username already exists"
// Code returns 102 for "email already exists"
// Code returns 104 for "internal server error"
// Code returns 202 for "user created successfully"

Refer register.php for complete code.

If the query succeeds, we capture the response in responseText variable. We can then do any response based manipulation we need for our specific needs. Just make sure to return false at the end to prevent default submit behavior. Here is my final jQuery snippet.

Finally, the entire HTML code has nothing more, just the standard doctype and stuff. Here is what to expect, or similar. LOL I was trying some CSS so ignore all that ;)
Also, I wanted to tell you, I switched from the classy syntax highlighter to this new (for me!) gist. It is cool, only a little more effort. Loved it. If you own a blog and post code frequently, give it a try. Thank you for reading.