16 Mar 2010

Beginners guide to a beautiful jQuery Form Pt. 2/2

Thumbnail for Beginners guide to a beautiful jQuery Form Pt. 2/2

By Jon Bergan (@jonbergan) in Input/Output » Tutorials

Welcome back! Did you miss me? Probably not, but that’s still cool. Where were we? Oh yes, in Part 1 of A Beginners Guide to a Beautiful jQuery Form, we stepped through the process of creating a simple web-based form, styling that form with some fairly basic CSS rules and adding some funky jQuery effects to make the form a little fancy.

This post will focus on the other half of the form – data validation and server-side scripting. We need data validation to ensure that the data being submitted by the user is valid and we need server-side scripting to send us an email once the form has been successfully submitted. Yes, yes, I know … it sounds daunting, but trust me – you’ll breeze through this if you got through the last one unscathed!

Where were we?

Before you begin, you’ll need to grab a copy of our new Working Files Pack relevant to this post. In this file, I’ve included the final source code for the PHP file, the JavaScript files and the CSS file. Please note though that as this code relies on server-side scripting (PHP), you probably won’t receive the email when you submit the form unless you have a copy of WAMP (Windows), MAMP (Mac) or something similar installed. Not too sure about this? Drop us a comment and we’ll fill you in!

Once you’ve got a copy of the Working Files Pack for Part 2 of A Beginners Guide to a Beautiful jQuery Form, you’re set. Dive right in!

We need some validation, people!

You’ve got the Working Files Pack, a fresh packet of barbeque Arnotts Shapes and you’re good to roll – right? Good. First things first. We need some data validation here. There’s no point letting users fill out a fancy form if we give them the option of filling it with junk. We want good quality data. And the best way to achieve this is with data validation.

Before we dig too deep, we need to add a simple rule to our CSS to style our error notices. To elaborate, whenever a user enters incorrect data or doesn’t complete a specific field, we want an error to appear. The CSS below will style this error for us. Feel free to go crazy with it. Make it look scary. Do whatever you need to do to ensure the user notices it and corrects their input. Check out the styles.css file in your Working Files Pack to see how I have added the CSS.

1
.error { display: none; border-bottom: 1px solid #be8181; color: #db2323; background: url(images/form-error.png) no-repeat #f3d9d9; padding: 4px 3px 0 22px; margin: 0 0 5px 0; font-size: 1em; height: 18px; font-weight: bold; }

Once you’ve added the above CSS to your stylesheet, we’ll need to make some adjustments to the markup in our original web form to allow these error notices to appear. The major changes can be found in the following code snippet on lines 5, 9, 19 and 23.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<form method="post" action="index.php" class="contact-form">
	<fieldset class="contact-form">
		<legend>So, who are you?!</legend>
 
		<div id="error_name" class="error"></div>
		<label for="contact_name">Lets start with your name. Introduce yourself!</label>
		<input type="text" name="contact_name" id="contact_name" value="Your name" class="contact-form" />
 
		<div id="error_email" class="error"></div>
		<label for="contact_email">Whats your email address? Don't worry, we won't spam you. Promise.</label>
		<input type="text" name="contact_email" id="contact_email" value="Your email address" class="contact-form" />
 
		<label for="contact_website">What about your website? Do you have one??</label>
		<input type="text" name="contact_website" id="contact_website" value="Your website URL" class="contact-form" />
	</fieldset>
	<fieldset class="contact-form">
		<legend>Whats on your mind?</legend>
 
		<div id="error_subject" class="error"></div>
		<label for="contact_subject">What are you emailing us about? You have to have some idea!</label>
		<input type="text" name="contact_subject" id="contact_subject" value="Type your subject here" class="contact-form" />
 
		<div id="error_message" class="error"></div>
		<label for="contact_message">Okay, you can start typing away here:</label>
		<textarea name="contact_message" id="contact_message" class="contact-form">Type your message here</textarea>
	</fieldset>
	<p><input type="submit" name="contact_submit" id="contact_submit" value="Send message" class="contact-submit" /></p>
</form>

You’ll notice that on lines 5, 9, 19 and 23, I’ve added a number of small <div> tags to the markup. These will act as placeholders for our errors when and if the errors need to appear.

Let’s just look at these a little closer shall we? Each <div> element has two attributes. The first being its id and the second being its class. The class attribute is set to "error" on each element to ensure that all of the error notices look the same. The id attribute on the other hand is unique for each error. These have been labeled so that we can identify each one with an error notice applicable to the field that is below it.

These might seem a little pointless now but don’t worry – we’ll come back to them in a little bit. For now, we need to finish up our changes to our new web form by calling a JavaScript function whenever the form is submitted. We can do this by adding the onsubmit attribute to the <form> element as shown below.

1
<form method="post" action="index.php" onsubmit="javascript:return checkContactForm();" class="contact-form">

Adding onsubmit="javascript:return checkContactForm();" to the <form> element basically tells your web browser to call the JavaScript function checkContactForm() whenever the form is submitted. So, logic tells us that if the form is going to be calling some ridiculously awesome function, we probably need to add that function to our JavaScript Files.

The following function should be added to your scripts/form-effects.js found in your Working Files Pack. Throw this into place and then we’ll proceed to step through this script so you know exactly what’s happening here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
var speed = 300;
 
function checkContactForm()
{
	var errors = false;
 
	resetFormErrors();
 
	if ($('#contact_name').val() == '' || $('#contact_name').val() == 'Your name')
	{
		$('#error_name').html('Geez! You could at least tell us your name!');
		$('#error_name').fadeIn(speed, function() { $("#error_name").effect("highlight", {color:'#f07878'}, 1000); } );
		errors = true;
	}
 
	if ($('#contact_email').val() == '' || $('#contact_email').val() == 'Your email address')
	{
		$('#error_email').html('We\'ll need an email address from you so we can reply to your message!');
		$('#error_email').fadeIn(speed, function() { $("#error_email").effect("highlight", {color:'#f07878'}, 1000); } );
		errors = true;
	} else {
		if (checkEmailAddress($('#contact_email').val()) == false)
		{
			$('#error_email').html('That email address doesn\'t look valid. Maybe try another one?');
			$('#error_email').fadeIn(speed, function() { $("#error_email").effect("highlight", {color:'#f07878'}, 1000); } );
			errors = true;
		}
	}
 
	if ($('#contact_subject').val() == '' || $('#contact_subject').val() == 'Type your subject here')
	{
		$('#error_subject').html('No subject? No response! Sorry!');
		$('#error_subject').fadeIn(speed, function() { $("#error_subject").effect("highlight", {color:'#f07878'}, 1000); } );
		errors = true;
	}
 
	if ($('#contact_message').val() == '' || $('#contact_message').val() == 'Type your message here')
	{
		$('#error_message').html('You\'ll need to type your message below so we have something to read!');
		$('#error_message').fadeIn(speed, function() { $("#error_message").effect("highlight", {color:'#f07878'}, 1000); } );
		errors = true;
	}
 
	if (errors == true)
		return false;
 
	return true;
}

Just like last time, this script seems crazy but its not. It’s really just a bunch of simple functions strung together amongst some if statements that think they’re pretty cool. They aren’t. Well, they kinda are but thats besides the point. Don’t let them worry you! I’m going to step through this script line for line (or close to it) so you too can read this code as if it were English.

Line 1: This first little line is declaring a new variable named speed and we’ll be using this little fella to specify how quickly animations occur throughout the form. For instance, when the error messages appear, they fade in and flash red to alert the user. We use this variable to tell jQuery how quickly these animations should run for. This value is in milliseconds so set it to whatever you like!

Line 3: Once again we have our friend function declaring a function called checkContactForm(). By now you should know what this line means as I went into a little more detail in the previous post.

Line 5: Here we are with another variable called errors. This variable basically holds the status of the data validation as we check the form. If we run into an error, we’ll be setting errors to true so the script knows that we’ve encountered a problem. You’ll see what I mean shortly.

Line 7: Similar to the onsubmit attribute we added to the <form> element earlier, we’re now calling a JavaScript function from within another function. The function we’re calling is named resetFormErrors() and it’s used to hide all of the errors that appear on the screen. We need to do this in case the user submits the form again and still runs into problems. If we don’t hide all of the errors before we validate the form on the second time round, the old errors will still be on the screen.

Line 9: Here we have one of our if statements that’s checking the data in our contact_name field. This if statement basically reads as follows:

If the contact_name field is blank or the contact_name field contains the text string "Your name", run the following commands for me please.

I elaborated on if statements in our previous post also so it may be worth checking that one out also to get a better understanding of these nasty little buggers.

Line 11: So, the if statement above basically checked to see if our contact_name field was empty or still contained the descriptive text we placed in it originally. If the field did contain either of these values, the code on lines 11-13 would be run. You guessed it – that means that lines 11-13 are used to display the error on the screen for that specific field. This line in particular sets the message that will appear in the <div> element we created earlier called error_name. Feel free to change this to something a little more appropriate.

Line 12: The next line is a little jQuery animation function called fadeIn. It allows us to fade an element in from zero opacity to 100% opacity. It’s a great way of bringing new elements onto the canvas as people are usually drawn to the animation even if it is fairly basic.

Line 13: We now come back to our trusty sidekick errors. Yeah, we’re ratting on the end user and letting errors know that we’ve encountered a problem. We do this by setting errors to true.

Line 44, 45 and 48: These final lines of the script basically tell the <form> element how we went with our data validation. If errors is equal to true, we had a problem so don’t let the user submit the form. If errors does not equal true, submit the form. Nice and easy!

Everything inbetween: The rest of the code is much of the same. We’re basically doing a number of similar tests on each of the other fields in the form and then having errors appear if those fields were completed incorrectly. Try and have a read through the rest of the script and see if you understand it all. Got a question? Please leave a comment!

Now, you may recall that at the start of the above JavaScript, we called a function called resetFormErrors(). As mentioned, this was used to hide any errors that may already be displayed on the screen due to a previous attempt at completing the form. This function is fairly standard and has been included below. Simply add it to your /scripts/form-effects.js file in your Working Files Pack.

1
2
3
4
5
6
7
function resetFormErrors()
{
	$('#error_name').fadeOut(speed);
	$('#error_email').fadeOut(speed);
	$('#error_subject').fadeOut(speed);
	$('#error_message').fadeOut(speed);
}

Below is the last piece of JavaScript you’ll probably have to look at during this tutorial. Thank the lords, I hear you scream! Don’t worry, I know the feeling. Sometimes you just want to ignore the scripting and hope that it’ll just all work, right? If only it were that simple.

This function is called checkEmailAddress() and it’s used to confirm that the email address provided in the web form is in fact a valid email address. It uses some basic regex to perform the task, and it works quite well.

1
2
3
4
5
6
7
8
function checkEmailAddress(str) {
	var goodEmail = str.match(/\b(^(\S+@).+((\.com)|(\.net)|(\.edu)|(\.mil)|(\.gov)|(\.org)|(\..{2,2}))$)\b/gi);
 
	if (goodEmail)
		return true;
	else
		return false;
}

Add the above code to your /scripts/form-effects.js file in your Working Files Pack and be done with it!

We’re validating!

Wow! If you browse to your test file (or our live demo), you’ll see that the form now validates the data you submit! Try leaving all of the fields blank or entering an invalid email address. You’ll soon get prompted with some nasty messages advising you to correct your data before proceeding. Awesome huh!?

Web Form displaying awesome validation notices

I want it to email me. Now!

We’re now officially done with all of the client-side scripting. No more JavaScript today, kids. We now delve deep into the world of PHP to wrap things up. PHP will basically allow us to grab the data the user has submitted and email that data to us in a nicely formatted email. For today, we’ll simply send a formatted text-only email but you could easily change this to a HTML layout without much hassle.

We firstly need to add to the top of our index.php file some PHP script that will actually send our email for us. This is a function called sendEmail() and it works in the exact same way as a JavaScript function. Its basically there to serve a single purpose and in this instance, it sends an email!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
function sendEmail ($to, $subject, $message)
{
	$headers = "From: Your Name <your@emailaddress.com>
Date: ".date('r')."
MIME-Version: 1.0
Content-type: text/plain; charset=iso-8859-1
X-Mailer: PHP/".phpversion();
 
	$subject = '[Website Name] '.$subject;
 
	mail($to, $subject, $message, $headers);
}
?>

I’m not going to go into too much detail regarding the PHP as I feel that PHP really is a whole other kettle of fish. Getting into server-side scripting isn’t easy but its not rocket science either if you want to start scratching the surface.

In a nutshell, the above script basically tells the MTA or mail server who the message is from, when it was sent, the content type for the message (text/plain or text/html are the most popular) and what the subject will be. Dive in and change these around. Set the subject to whatever you want it to be and be sure to modify who the message is being sent from. Customize this function to your hearts content!

Secondly, we need to add another block of PHP code just above the <form> element and also just below it. The following PHP script shows you where we’ve added the code in relation to the <form> element. I haven’t included all of the markup from the web form as this would simply be too large.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?php
 
if (isset($_POST['contact_name']) && isset($_POST['contact_email']) && isset($_POST['contact_subject']) && isset($_POST['contact_message'])) 
{
	$body = 'Hi there,
 
The following user has submitted their details via the YourWebsiteHere Contact Form. 
 
Name          : '.$_POST['contact_name'].'
Email Address : '.$_POST['contact_email'].'
Website       : '.$_POST['contact_website'].'
 
Subject       : '.$_POST['contact_subject'].'
 
Message:
--------
 
'.str_replace(array("\r\n","\n",'<br>','<br />'), "\n", $_POST['contact_message']).'
 
------------------------------------------------------
End of message.';
 
	sendEmail('your@emailaddress.com', 'Contact Form Submission', $body);
?>
<h4>Thank you so much!</h4>
<p>Thanks alot for contacting us. <strong>Your message has been successfully sent!</strong> In all goes to plan, we should get back to you within 48 hours.</p>
<p>Please click <a href="index.php">here</a> to return to the Contact Form.</p>
 
<?php } else { ?>
 
<form method="post" action="index.php" onsubmit="javascript:return checkContactForm();" class="contact-form">
 	... form would appear here ...
</form>
 
<?php } ?>

Essentially this piece of code has three main tasks:

  • First it must check if the user has indeed submitted the form. If they have, send the email and if they haven’t, display the web form with or without errors.
  • If the user has submitted the form, style an email message to them containing each of the fields that they submitted via the web form. You’ll see the layout for the message here plain as day. Go ahead and modify it so that it reads how you want it to.
  • Once we have the message styled and ready to go, send the actual email and display a thank you message to the end user for submitting the form.

Take a look at the index.php file found in your Working Files Pack. You’ll see how I’ve formatted the file with the HTML and PHP code all included.

Also take note of the final brace (}) that is shown underneath the form. This final brace is required to finish off all of the PHP code above the form. You can blame those damned if statements for that one!

Got the PHP loaded and the files on a server that supports PHP? Run the script and submit the form! You should receive an email almost instantaneously containing the data you entered. If you do not, don’t fret. Drop us a comment. We’d be more than happy to take a look at your set up to see where you went wrong.

That’s it! It’s beautiful. Right?

No more ugly code and no more nasty CSS. Just an amazingly beautiful jQuery-driven web form that’s ready for every one of your users to submit. Customize the form and make it your own. Do whatever you like with it! Once you’ve created your masterpiece, drop us a comment or send us an email with your link – we’d love to see it in action!

On a parting note, we know these two articles have been excessively long, however we hope you have thoroughly enjoyed them. It’s important to have tutorials such as these so that we can cater for every level of developer – from newbie to pro. With that said though, would you prefer we provided video tutorials or step-by-step tutorials similar to this one? Let us know what you like. We always aim to please.

View Demo Download Source Code

Jon Bergan

By Jon Bergan

Jon is a passionate web designer, developer and blogger from Australia. Whilst online, he spends most of his time knee deep in PHP code or blogging about good design and business advice. He is also a movie lover, guitar fiend, tea drinker and serial entrepreneur.

You can find out more about Jon here or you can catch up with him online via Twitter or Facebook.

8 comments on this post

Show us some love and bookmark this post on your favourite social bookmarking sites!

Google Buzz
  • Digg
  • del.icio.us
  • Mixx
  • Google Bookmarks
  • NewsVine
  • Reddit
  • StumbleUpon
  • Technorati
  • email