Create a bullet-proof contact form

Note: This article has been marked for a quality review and will soon be updated.

Contact pages are usually one of the basic building blocks of any website, and while many simple feature an email address for spam bots to pick up and use, or even a handy 'mailto' link, the best ones feature a proper contact form. To make a bulletproof one we're going to need some thick glass and a riot shield PHP and JavaScript. Having those bad-boys on our side will ensure we can create a beautiful AJAX-enabled means of contact for our users. We also need to ensure our form will work on the rare occasion that a user has JavaScript turned-off *gasp* - I know, it's a scary thought, but I'm sure we'll figure something out!

So we'll start with some simple HTML to set out our fields, the following code is what we'll be working with:

<form id="contact" class="right" method="post" action="mail.php">
	<h3 class="hidden success"><br/>Message sent!</h3>
	<label>Name: <span class="warning right"></span>
		<input type="text" name="name" />
	<label>Email: <span class="warning right"></span>
		<input type="text" name="email" />

	<label>Message: <span class="warning right"></span>
		<textarea name="message"></textarea>
	<input class="right" type="submit" value="Send" />

Aside from the obvious, the form features a few extra elements - namely the .warning elements - we'll see what they're for in a moment. I also assume that you have the class of .right set up to float elements to the right; if now, then you'll need to float the affected elements individually in your CSS. Right, that's the HTML sorted, lets take a look at the JavaScript for this puppy.

function validateEmail(email){ 
	 var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ 
	 return email.match(re); 

	var name, email, message, errors;
	errors = 0;
	name = $('input[name=name]').val();
	email = $('input[name=email]').val();
	message = $('textarea[name=message]').val();
	if(name==''){ $('input[name=name]').siblings('.warning').text('This field is required!'); errors++; }
	if(email==''){ $('input[name=email]').siblings('.warning').text('This field is required!'); errors++; }
	if(message==''){ $('textarea[name=message]').siblings('.warning').text('This field is required!'); errors++; }
	if(!validateEmail(email)){ $('input[name=email]').siblings('.warning').text('Please enter a valid email!'); errors++; }
		var dataString = $(this).serialize() + '&js=true';
			url: 'contact-post.php',
			data: dataString,
			type: 'POST',
			success: function(data){
				$('form label, form input[type=submit]').slideUp(500, function(){
					$('form .success').hide().removeClass('hidden').slideDown(500);
	return false;

Now for the moment we'll ignore the validateEmail() function, and take a look at the form submission code. First off we set up some variables for the values in our form, this prevents us having to use longer code snippets and querying the DOM too much. Once we've got them set up we give the user the benefit of the doubt and remove any warning that may have previously been set by removing any text from the elements with the class of .warning. And then we validate the fields. The first three 'if' statements simply check that the user has entered a value in each field - if they haven't we tell them so, and increment our errors variable by 1. The last 'if' statement uses the validateEmail() function that we set earlier. There's no reason to worry if you don't understand how that function works, Regular Expressions are a world of their own. All we need to know, is that it tells us if the user has entered a valid email address.

Following our rather basic validation checks we then test to see if the form has passed - because we've been using our errors variable all along, if it's set to '0' we can rest assured nothing has gone wrong. If that's the case we serialise the form, and use a simple AJAX request to submit the data to our server. If our server is happy, we show our users a success message. Now all we need to do is set up our contact-post.php file, like so:

function redirect($hash){
		echo 'Invalid ' . $hash;
	}else {
		echo 'Message sent!';
		echo '<meta http-equiv="refresh" content="0;url=">';

		// Validate info here
		if(empty($_POST['name'])){ redirect('name'); }
		if(empty($_POST['email'])){ redirect('email'); }
		if(empty($_POST['message'])){ redirect('message');  }
		if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){ redirect('email'); }
	$sendto = '';

	$name = $_POST['name'];
	$email = $_POST['email'];
	$phone = $_POST['phone'];
	$message = $_POST['message'];
	$to = $sendto;
	$subject = "[MySiteName] Message";
	$message = "
	<title>Contact form Submission</title>
	<p style='font-family:Arial, Helvetica, sans-serif; color:black;'>The following was sent by <strong>".$name." (Email: ".$email."):</strong></p>
	<p style='font-family:Arial, Helvetica, sans-serif; color:black; font-size:16px;'>".nl2br(stripslashes($message))."</p>
	<p style='font-family:Arial, Helvetica, sans-serif; color:black;'>(Sent on: ".gmdate('d\/m\/y').")</p>
	$headers = "MIME-Version: 1.0" . "\r\n";
	$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
	$headers .= 'From: ' . $name;
}else {
        redirect('submission - no data entered!');

The function at the top will be used when we want to give the user some feedback - if they entered all the correct info, they'll be given a success message, and then redirected to your site in a timely fashion, otherwise they will be told what is wrong with their submission. Then we get to the guts of the script - we first make sure there is some data to play with - if there isn't we tell the user off, and if there is we go on to see if the user has JavaScript running. You may have noticed the little variable 'js' that we added to the serialised form back in our JavaScript - that is our way of finding out if the form is being submitted via an AJAX request in JavaScript - if the variable is empty, we let PHP validate our form's content - this is essentially identical to the JS code we used previously.

We then set up a really basic email, and send it to the address in the $sendto variable. Finally we redirect the user to the site. As a side note, do remember that this page will only be seen by users without JavaScript turned on.

And that's it! You now have a swanky contact form that, for all intents and purposes, is bullet-proof, but having said that, I wouldn't actually test that theory with a gun of any kind...

Tips & Tricks

Hide an element with jQuery whilst scrolling

Note: This article has been marked for a quality review and will soon be updated.

Today I came across an interesting problem that no amount of Google searches could solve. So I had to knuckle down and come up with a solution - and surprisingly it was much more simple that it had first appeared.

So the problem is hiding an element when a user is scrolling - it might be a menu, a header, or a picture of my cat, Sophie. Either way we can't just use the simple delay() function in jQuery to help us out - we need to use some raw JavaScript. To accomplish this we will create a variable into which we will place the current scroll amount of the page, we will then wait for a period of time, and check if that scroll amount has changed. If it has we will leave the element hidden, otherwise we'll show it to the user again.

And here's the rather simple code to do just that:

	var scrollA = $('body').scrollTop();
		if(scrollA == $('body').scrollTop()){
	}, 200);

And there we have it! A really simple effect made easy with a tiny bit of JavaScript.

You can check out the fiddle over here:

Tips & Tricks

Force JS replace to work on all occurrences of needle

When manipulating strings in JavaScript a useful method to know about is the replace() method. It take 2 parameters - the needle and the haystack. So if you wanted to replace 'cat' with 'dog' it might look something like this:

var myString = "The cat jumped over the fence";
var myNewString = myString.replace("cat","dog");

Great it worked. You can also use regular expressions for the needle if you're into that kind of thing - say for instance, if you want to generate a valid URL. It when doing just that, that I realised I had a problem on my hands. My code used 2 replace methods - one for removing special characters, the other to remove spaces. The first was a regular expression, while the second was a basic method searching for a space and replacing it with a dash. My problem was that it was only replacing the first space. And so I had to reach for a regular expression to help me out.

Don't worry if you're not too great with RegEx, this one is really basic, and here's what it looks like:

var myString = "The cat jumped over the fence to meet another cat."
var myNewString = myString.replace(/cat+/g,'dog');

That bit of code tells the rendering engine that we are using a RegEx with our forward slashes, inside we have the word we are looking to replace, then the plus symbol tells it to match the preceding word (in our case 'cat'), 1 or more times. Then the magic happens - we use the 'g' character to tell it to look for all occurrences.

And that is how you ensure all occurrences of a needle are replaced when using the replace() method. Hopefully this article will save you scratching your head over why a seemingly obviously method won't play ball.


Using Location Awareness

A future web design trend that I predict is location awareness, and using it to ensure a better user experience. However without access to GPS, most of the world's desktop PCs will have to rely on other means of telling servers where they are. One way that we can use today to determine the location of any given computer is by using a user's IP address and feeding it to a service that will tell us where the computer is located. Now while this sounds great in practice, in reality most services aren't all that accurate. But saying that, most can tell you what country a user is visiting from. So how can we use this is web design?

Well say for instance you have two e-commerce sites that are essentially the same shop - one for your American audience, and one for the UK. Differences might include currency conversions and product listings, and it would be nice to be directed to the right site should you accidentally visit the wrong one. For example Crucial's website alerts the user with a nice little pop-up, asking them if they would like to visit their international site, as it were, as you can see below.

Crucial Popup

This sort of interaction is really beneficial to the user because it stops them making mistakes later on, and more importantly, it's easy to accomplish!

Now instead of presenting you with all the code, I'm going to tell you how I accomplished the desired effect - hopefully I'll make you actually think about how it works 🙂

So first off I visited this code snippet page to get my code for finding out where the user is. I then took the array filled with information and used an "if" statement to evaluate it. So something like...

if($ipInfo["country"]=="GB - United Kingdom"){
  echo '<script type="text/javascript">popup();';

The code above will initiate a JavaScript function if the user appears to be coming from the UK. This function would do anything you want really, I would suggest you use a nice pop-up box to alert the user, much like the one shown above, and then allow them to navigate to another site. I would argue against immediate redirection, because the reliability of a free database cannot be ensured, and you wouldn't want to be redirected to the wrong site without the option to navigate back, now would you?

As I said, this is a really easy way of determining where your users are, and making a decision based on that information. Users will thank you for helping them out, and admire the fact that you know where they live!*

*Users may not be impressed by this simple technique 😉

Tips & Tricks

Get going with jQuery!

If you would have asked me 6 month ago what I thought of Javascript, I would have told you I thought it was a precarious language which never worked for me - and that's coming from a semi-programmer! To me the language was cumbersome and seemed like it was cobbled together in a very short time with little regard for the developers (don't shoot me!) . For me I didn't have the time to sit down and trawl through documentation on how to use it, and the idea of writing 100s of lines of code for little gain didn't appeal to me.

However a short time ago I was introduced to jQuery - a Javascript library, and I must say it was one of the best gifts I have ever received. jQuery replaces the annoying syntax of Javascript and introduces an easy to use set of tools that can be implemented by someone with little programming experience. Gone are the days when I spend hours trawling over Javascript code to find errors - now I can reel off 50 lines of jQuery without ever making a mistake! Furthermore it's ease of use means that there are loads of websites advocating it. It is free to download - just search for jQuery, and as I say - easy to use.

jQuery allows you to easily animate elements in a slick and stylish manner - making your websites look far smoother. Integration with AJAX means that form validation is also really easy, and best of all - the documentation is amazing!

So what does it look like?


Would select a div element. Then to manipulate it and say fade it in, you would simply add -


The "1000" indicates the length of the animation - in milliseconds. You can even animate individual CSS properties like so -

$("#myDiv").animate({ background-color:"#000"; }, 2500)

And to react to events use functions such as -

$("body").on('click', '#myDiv', function(){ $("#myDiv").animate({ top:"50px"; }, 2500) });

jQuery is a really simple library to learn your way around, and I would recommend going with it because of it's ease of use alongside the powerful features that it possess! If you have never tried jQuery I would seriously suggest you do; I remember when I first discovered it, I spent about a week just playing around with it animating red squares and other random elements, and I think you should do the same - eventually integrating it into a site of your own!