Creating a Facebook-like Registration Form with jQuery

Introduction

Facebook is a showcase of great UI design. And as it has become a major part of our lives, it has also raised the bar for web development, pushing developers to meet higher expectations.

This however has a good side – it challenges web developers and designers to better themselves and constantly improve their work.

In this tutorial, we are going to learn from the best, and create a facebook-like sign up form. So go ahead and download the demo files to start learning!

The XHTML

We start off by laying down the XHTML backbone, as seen in index.php in the demo files:

<div id="div-regForm">

<div class="form-title">Sign Up</div>
<div class="form-sub-title">It's free and anyone can join</div>

<form id="regForm" action="submit.php" method="post">
<table>
<tbody>
<tr>

	<td><label for="fname">First Name:</label></td>
	<td><div class="input-container">
	<input name="fname" id="fname" type="text" />
	</div></td>

</tr>
<tr>

	<td><label for="lname">Last Name:</label></td>
	<td><div class="input-container">
	<input name="lname" id="lname" type="text" />
	</div></td>

</tr>
<tr>

	<td><label for="email">Your Email:</label></td>
	<td><div class="input-container">
	<input name="email" id="email" type="text" />
	</div></td>

</tr>
<tr>

	<td><label for="pass">New Password:</label></td>
	<td><div class="input-container">
	<input name="pass" id="pass" type="password" />
	</div></td>

</tr>
<tr>

	<td><label for="sex-select">I am:</label></td>
	<td>
	<div class="input-container">
	<select name="sex-select" id="sex-select">
	<option value="0">Select Sex:</option>
	<option value="1">Female</option>
	<option value="2">Male</option>
	</select>

	</div>
	</td>
</tr>
<tr>
	<td><label>Birthday:</label></td>
	<td>

	<div class="input-container">

	<select name="month">
	<option value="0">Month:</option>
	<?=generate_options(1,12,'callback_month')?>
	</select>

	<select name="day">
	<option value="0">Day:</option>
	<?=generate_options(1,31)?>
	</select>

	<select name="year">
	<option value="0">Year:</option>
	<?=generate_options(date('Y'),1900)?>
	</select>

	</div>

	</td>

</tr>
<tr>

	<td>&nbsp;</td>
	<td><input type="submit" class="greenButton" value="Sign Up" />
	<img id="loading" src="img/ajax-loader.gif" alt="working.." />
	</td>

</tr>

</tbody>
</table>

</form>

<div id="error">
&nbsp;
</div>

</div>

We begin by creating a div container for the form, to which we assign the id div-regForm. In it we are going to position the various form components.

Later we create the headings of the form, properly styled with CSS, as you’ll see later.

Then we have the form itself. A note here would be to remember that the form does not actually get submitted by its own – its all done via AJAX, which means that it doesn’t really matter what you are going to put in the method and action attributes.

Inside the form, we position a table, which will allow us to easily create a grid layout for the form labels and fields. There’s been a debate on using tables in this manner since div layout came to fashion, but mind you that facebook itself is using the same technique, which automatically wins it for me.

Every input field has a respective label element serving as a, you guessed it – a field label. We are even using the for attribute, which means that by clicking the label, you select the textbox on the right.

Next comes a select box and after this we have 3 very interesting lines, that I’ve highlighted for you. We use a neat little PHP function to generate all the option elements that go into the select boxes comprising the selection of a birth date. We will talk about this in a minute.

Later we have the Sign Up button, and a little gif, which is hidden by default and shown only when AJAX requests are in progress.

The last div element is our error container, also hidden by default.

Our facebook-like form

Our facebook-like registration form

The CSS

In order to convert our plain XHML coding into something eye-catching and facebook-likey, we need some serious styling.

Lets take a look at our CSS, as defined in demo.css.

/* Page styles */

body,h1,h2,h3,p,td,quote,small,form,input,ul,li,ol,label{
	margin:0px;
	padding:0px;
}

body{
	margin-top:20px;
	font-family:Arial, Helvetica, sans-serif;
	color:#51555C;
	height:100%;

	font-size:11px;
}

/* Form styles */

input,select{
	padding:3px;
	color:#333333;

	border:1px solid #96A6C5;
	margin-top:2px;
	width:200px;
	font-size:11px;
}

select{
	width:auto;
	padding:2px;
}

.formline{
	padding:3px;
}

label{
	font-size:11px;
	text-align:right;
}

table{
	width:300px;
}

td{
	font-size:11px;
}

.input-container{
	padding:1px;
}

#div-regForm,.registered{
	border:3px solid #eeeeee;
	padding:15px;

	background:url(img/bg.jpg) repeat-x #cbd4e4;
	color:#203360;

	margin:30px auto 40px auto;
	width:400px;
}

.form-title,
.form-sub-title{
	font-size:20px;

	font-family:"Lucida Grande",Tahoma,Verdana,Arial,sans-serif;
	font-size:20px;
	font-weight:bold;
}

.form-sub-title{
	font-weight:normal;
	padding:6px 0 15px 0;
}

.greenButton{
	width:auto;
	margin:10px 0 0 2px;
	padding:3px 4px 3px 4px;
	color:white;
	background-color:#589d39;
	outline:none;
	border:1px solid #006600;
	font-weight:bold;
}

.greenButton:active{
	background-color:#006600;
	padding:4px 3px 2px 5px;
}

#loading{
	left:10px;
	position:relative;
	top:3px;
	visibility:hidden;
}

#error{
	background-color:#ffebe8;
	border:1px solid #dd3c10;
	padding:7px 3px;
	text-align:center;
	margin-top:10px;
	visibility:hidden;
}

Lines 1-6 are where we reset some of the XHTML elements, to ensure that they appear the same in all browsers.

We continue with styling the body section and start styling the form elements.

The first elements we style are input and select. Select shares most of its styling with input, but also differs in width and padding, so we put an additional set of styles to cover them.

Its mostly widths and paddings down to line 81, where we style our sign up button. We have styles for both the normal, non-pressed state, and the active, pressed state. What the active state does, is that it moves the text label of the button to the bottom – right with one pixel, while darkening the background, which gives the illusion of the button being pressed.

The last two styles are #loading and #error, which select the respective elements by their ID’s and hide them with visibility:hidden by default. We will only show them with jQuery when it is appropriate.

The PHP code

Remember, when a few minutes ago I mentioned about the generate_options PHP function?
Here it is, taken right from our functions.php file:

function generate_options($from,$to,$callback=false)
{
	$reverse=false;

	if($from>$to)
	{
		$tmp=$from;
		$from=$to;
		$to=$tmp;

		$reverse=true;
	}

	$return_string=array();
	for($i=$from;$i<=$to;$i++)
	{
		$return_string[]='
		<option value="'.$i.'">'.($callback?$callback($i):$i).'</option>
		';
	}

	if($reverse)
	{
		$return_string=array_reverse($return_string);
	}

	return join('',$return_string);
}

function callback_month($month)
{
	return date('M',mktime(0,0,0,$month,1));
}

/* and here is how we use it (taken from our XHTML code above):
generate_options(1,31);				// generate days
generate_options(date('Y'),1900);			// generate years, in reverse
generate_options(1,12,'callback_month');		// generate months
*/

This is a neat little peace of code. Now lets explain what it does.

The first thing you notice in our generate_options function are the parameters $from and $to for the range of options to be generated (days, months and years in our case), and an optional parameter $callback, which is a callback function (more on that in a moment).

Inside the function, we define $reverse as false. If we use the function in the following manner: generate_options(1,31), we are just generating a series of option elements and outputting them in the same order. If we switch the positions of the parameters the output is in reverse order.

This is exactly what we do in line 5. We check if the range of $from and $to is reversed and setting $reverse to true. But in the same time, we are exchanging their values, so that we use the same for construct as in our normal generation.  If we haven’t done this we would have had to write another for to do this job.

Next we fill an array called $return_string with the generated options, reversing it if necessary and outputting it as string by joining the array elements.

Remember the $callback I talked about earlier? Here comes its part. On line 18 we check if  a $callback was supplied – as in generate_options(1,12,’callback_month’), and if it was, we execute the function and supplying the current $i counter’s value. In practice, it is the same as if we were doing callback_month($i).

Later we have the callback_month function, which we use as a callback in the month generation. It basically takes an integer parameter (our $i above), and returns the month name as string.

The jQuery source

Ok, now that we have completed the form’s looks, we need to be able to send the data over to the PHP backend where it is processed. For this purpose, we are using jQuery, which you can include in page by putting these lines of code in your page’s head section:

<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</script>

The library is automatically included from Google’s CDN. After that you can use jQuery’s ajax method.

Here is the code located in script.js.

$(document).ready(function(){

	$('.greenButton').click(function(){

		register();

	});

	$('#regForm').submit(function(e) {

		register();
		e.preventDefault();

	});

});

function register()
{
	hideshow('loading',1);
	error(0);

	$.ajax({
		type: "POST",
		url: "submit.php",
		data: $('#regForm').serialize(),
		dataType: "json",
		success: function(msg){

			if(parseInt(msg.status)==1)
			{
				window.location=msg.txt;
			}
			else if(parseInt(msg.status)==0)
			{
				error(1,msg.txt);
			}

			hideshow('loading',0);
		}
	});

}

function hideshow(el,act)
{
	if(act) $('#'+el).css('visibility','visible');
	else $('#'+el).css('visibility','hidden');
}

function error(act,txt)
{
	hideshow('error',act);
	if(txt) $('#error').html(txt);
}

The first lines of code in $(document).ready get executed after the page has loaded and bind our register() function with the button’s onclick event and our form’s onsubmit event utilizing the preventDefault() method in order to stop the form from being submitted.

And here is the simplicity of the $.ajax method (line 23) – in a few lines of code we send to submit.php by POST all of regForm’s fields (regForm is the ID of our registration form). We receive a response in JSON format (for more on that later) which gets processed by the function given in success. In this example (lines 30-37) we process the returned object and decide whether to show an error, or redirect to a registered-user-only page.

Later we have the hideshow() function which hides or shows an element on the page (for example the rotating gif animation on our form) and the error function which manages the displaying of errors on the form.

But how do we decide whether the information in the form is correct, and where to redirect the user if it is?

This is done in submit.php:

// we check if everything is filled in

if(empty($_POST['fname']) || empty($_POST['lname']) || empty($_POST['email']) || empty($_POST['pass']))
{
	die('{status:0,txt:"All the fields are required"}');
}

// is the sex selected?

if(!(int)$_POST['sex-select'])
{
	die('{status:0,txt:"You have to select your sex"}');
}

// is the birthday selected?

if(!(int)$_POST['day'] || !(int)$_POST['month'] || !(int)$_POST['year'])
{
	die('{status:0,txt:"You have to fill in your birthday"}');
}

// is the email valid?

if(!(preg_match("/^[\.A-z0-9_\-\+]+[@][A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z]{1,4}$/", $_POST['email'])))
	die('{status:0,txt:"You haven\'t provided a valid email"}');

echo '{status:1,txt:"registered.html"}';

Here we check some of the most typical error situations. Every message, that we output, has to be formatted as a javascript object with status and txt properties. They are accessible in our AJAX as msg.txt and msg.status. The main idea here is that errors return a status with a value of 0 and a successful registration returns a status 1, with txt being a URL of a resource accessible only for registered users.

*Note that you’ll have to add code for inserting new database records, creating sessions and a few more error checks on your own, depending on your needs.

And with that our form is finished.

Conclusion

Today we created a fancy looking and functional registration page, inspired by no other than facebook itself. We successfully used jQuery and the $.ajax method to create a real time, asynchronous registration form, complete with error checking and browser redirects.

Powered by Gewgley