Enhancing a PHP Contact Form with JavaScript

Enhancing a PHP Contact Form with JavScript

It's always important for your customers and visitors to be able to contact you with ease. One of the easiest ways for a customer to get in contact with you is by using a contact form on your website. This is when the customer can fill out text boxes with their details as well as provide a message and these details will be emailed to the recipient (you). I'm going to show you how to create a contact form using XHTML, CSS, JavaScript and PHP. Using these languages you are able to make an interactive contact form that users can fill out quickly and easily.

Demo Here | Source Images (not files)


The HTML

The first step to do is to create our two main files, the first one is form.html, which will show the form, and the second is style.css, which will have all of our styles which will affect how the form looks. Let's start with form.html, we need to add in the basic html elements.

<html>
<head>
<title>Contact Us Demo</title>
<link href="style.css" type="text/css" />
<script src="js.js" type="text/javascript"></script>
</head>
<body>

</body>
</html>


Now we need to get our basic structure up, using the source images, we have 5 main div tags we need to create.

<div id="container">
	<div id="contact-us">
		<img src="top.jpg" width="498" height="65" />
	</div>
	<div id="contact-top">
		<img src="contact-top.jpg" width="498" height="46" />
	</div>
	<div id="contact-mid">
		<!-- FORM HERE -->
	</div>
	<div id="contact-bot">
		<img src="contact-bot.jpg" width="498" height="45"  />
	</div>
</div>


So we have our container div, which help centre our structure and bring it down on the page more. We then have the contact-us div, which holds our image that says "Contact Us". Our next three div tags are for the form structure. The top and bottom both hold images that we do not want disturbed, the middle is where the form will be.


The Form

Our next step is to create the form. We won't be using form labels like you would see on most contact forms, instead we are going to have ours on the text boxes themselves, and have them move above the text boxes when the user starts writing. To do this, we have these labels in a separate div tag.
<form method="post">
	<div id="your-name">
		Your Name
	</div>
	<input
		type="text"
		name="name"
		id="name"
		class="input-box"
		value=""
		onFocus="move('name', 'your-name', 1);"
		onBlur="move('name', 'your-name', 0);"
	/>
	<span id="nameerror"></span>
</form>
So now we have our label and our input box. Our input boxes using an onFocus and onBlur event, onFocus is fired when the user selects the text box. onBlur triggers when the user has taken the cursor off the text box and can no longer write in it. Both of these call to a JavaScript function that will move our label off the text box, and above it, or otherwise move it from above, back onto the text box if the field is empty. There are three arguments in this function, they are as followings:

move( input, label, up or down );


The last bit in this section of code is a span tag called "nameerror". This will show any errors the field has when the user tries to submit the form. Now we need to do this for two more fields, email field and a message field.
<br /><br /><br />
<div id="your-email">
	Your Email
</div>
<input 
	type="text" 
	name="email"
	 id="email" 
	class="input-box" 
	value="" onFocus="move('email', 'your-email', 1);" 
	onBlur="move('email', 'your-email', 0);" 
/>
<span id="emailerror"></span>
<br /><br /><br />
<div id="your-message">
	Your Message
</div>
<textarea
	name="message"
	id="message" 
	class="text-box" 
	onFocus="move('message', 'your-message', 1);" 
	onBlur="move('message', 'your-message', 0);"
></textarea>
<span id="messageerror"></span>
<br /><br /><br />

<input 
	type="button"
	 name="send"
	id="send" 
	class="button" 
	value="" 
	onClick="submitForm( );" 
/>

<span id="response"></span>


As you can see, we don't use a submit button at the end, we just use a normal button field with an onClick function. This will check all the data and if there are no errors, use AJAX and PHP to email the data without having to reload the page multiple times. The span tag with an id of response is where the response from the server (after sending the form) will show up.


The CSS

Our CSS isn't very big, but it will make the form look great. We won't be styling any tags apart from the div tags we created. To start off with is the container tag. If you didn't know already a html tag can only have one id but many class attributes, also a class defined style can be applied to many html tags, this makes classes a much more flexible means to attach styles to. To attach your tag to styles for an id you use a hash ( # ) whereas with class you use a period ( . ).

#container {
	width: 498px;
	margin: 200px auto;
	border: 1px solid #000;
}


So our container is 498px wide, with a 1px black border. We also use margin to set it in the centre of the page and 200px down the page. Our next bit is to style the basic structure.

#contact-us, #contact-top, #contact-bot {
	width: 498px;
}
#contact-mid {
	width: 438px;
	background: url( contact-mid.jpg ) repeat-y;
	padding: 0 30px;
	font: normal 12px Tahoma, Verdana, Arial;
	letter-spacing: 0.1em;
}


Notice that we use short-hand, you can see that we use a background image that repeats on the Y axis (top to bottom) on our middle contact structure combined in one style attribute. Our next css is going to be for the labels, and setting them so that they are over the input fields.

#your-name, #your-email, #your-message {
	position: absolute;
	margin: 8px 0 0 6px;
	color: #a4a4a4;
}


We use absolute positioning so they show up above the text fields and use margins to set them in the proper position above their respective text fields.

.input-box, .text-box {
	width: 231px;
	height: 29px;
	padding: 5px;
	background: url( text.png ) no-repeat;
	border: none;
	font: normal 12px Tahoma, Verdana, Arial;
	letter-spacing: 0.1em;
}
.text-box {
	background: url( box.png ) no-repeat;
	height: 112px;
}
.button {
	width: 102px;
	height: 30px;
	background: url( send.png ) no-repeat;
	border: none;
}


The code above is the rest of the css. These style the fields and the button. As you can see, we have these as a class, since we apply multiple times, we also have separate images for each of them.


The JavaScript

Our JavaScript has 4 functions to it. The first function we'll create is the move function, this function will move the labels accordingly.

function move( input, div, onoroff ) {

}


Input is the id of our input field, div is the id of the label, and onoroff indicates whether we should take the label off or on the field, this will be either a 1 or 0, 1 means we are taking it off the field.

var value = document.getElementById( input ).value.split(' ').join('');
if( onoroff == 1 ) {
	document.getElementById( div ).style.margin = '-20px 0 0 6px';
} else {
	if( value == "" ) {
		document.getElementById( div ).style.margin = '8px 0 0 6px';
	}
}


The first line will take off all spaces, so something similar to "Hello World" will become "HelloWorld". We do this because if the user enters a space, then the labels will not move back over the text field.

Our next function is setting up our AJAX, getting the HTTP Request.

function makeObject(){
	var x;
	var browser = navigator.appName;
	//If IE
	if(browser == "Microsoft Internet Explorer"){
		x = new ActiveXObject("Microsoft.XMLHTTP");
	}else{
		//other browsers
		x = new XMLHttpRequest();
	}
	return x;
}

//Make request
var request = makeObject();


Now we need to make a new function that will handle our form when submitted. This function will check to make sure the fields are filled in, and that the email has a correct format. It will then send the data to another file to be emailed.

function submitForm( ) {
	var name = document.getElementById('name').value);
	var email = document.getElementById('email').value;
	var message = document.getElementById('message').value;
	var filter = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
	var error = false;

	//Set all error spans empty
	document.getElementById("nameerror").innerHTML="";
	document.getElementById("emailerror").innerHTML="";
	document.getElementById("messageerror").innerHTML="";

	if(name.split(' ').join('') == "" ) {
		document.getElementById("nameerror").innerHTML = "Field is Empty.";
		error = true;
	}

	if( !filter.test( email ) ) {
		document.getElementById("emailerror").innerHTML = "Email is Invalid.";
		error = true;
	}

	if(email.split(' ').join('') == "" ) {
		document.getElementById("emailerror").innerHTML = "Field is Empty.";
		error = true;
	}


	if(message.split(' ').join('') == "" ) {
		document.getElementById("messageerror").innerHTML = "Field is Empty.";
		error = true;
	}

	//if no errors
	if( error == false ) {
		//Set line breaks as double underscore ( __ ), we will change this back later
		message = message.split('\n').join('__');
		//send data using get method to sendform.php
		request.open('get', sendform.php?name='+ name +'&email='+ email +'&message='+ message);
		request.onreadystatechange = parseInfo;
		request.send('');
	}
}


We have one more function to create, this is parseInfo, which will get the response from the server and show it on the page. We use readyState to check to see if the page is ready or not, if it's not ready, it will show a loading image, otherwise it will show the response.

function parseInfo() {
	if( request.readyState == 1 ) {
		document.getElementById('response').innerHTML = 'Loading...';
	}
	if( request.readyState == 4 ) {
		var answer = request.responseText;
		document.getElementById('response').innerHTML = answer;
	}
}


That is all of our JavaScript done. Make sure you save this in the file called js.js since it's what we used in the html.


The PHP

This is the part where we finally send the email. Since PHP processes pretty fast, we should use a sleep so that the loading stays on a little bit longer, just make it look like we are actually processing something.

<?php
sleep( 3 );


Sleep will delay the page from any processing until the amount of seconds is counted, in our case, 3 seconds. This is useful for small applications like this, but for large applications when using databases, especially when getting large amounts of data or searching through more than a million rows in a database, it is not recommended to use sleep since this may take more than a few seconds.

Our next step is to get all the data into variables. If you remember in our JavaScript code, we used the GET method to send our data through to the page.

$name = $_GET['name'];
$email = $_GET['email'];
$message = $_GET['message'];


Now we need to change some strings in the message variable. Since we encoded our message for the URL in the JavaScript, we can use PHP to decode the URL. When data is sent, single quotes automatically get a slash in front of them. We also swapped line breaks ( \n ) in the JavaScript with a double underscore, __. We had to do this since these line breaks cannot be passed through a GET query. This means we can now change it back so that the email will look how it is meant to.

$message = stripslashes( $message );
$message = str_replace( '__', "\n", $message );


Our final step is to send the email, and notify the user whether it was sent successfully or not.

$headers = 'From: ' .$name . '<' .$email .'>' . "\r\n";
$to = your@email.com;
if( mail( $to, 'Subject Here', $message, $headers ) ) {
	echo 'Email sent successfully.';
} else {
	echo 'The email could not be sent.';
}
?>


So in here, we set two new variables. The first one is headers, which contains who the email is from. In this case, we set "from" as the name of the user. The second variable will contain the email address, which is where the email is going.

We then use an if statement to create a message that will inform the user whether or not the email was sent.


Demo

That's it for this tutorial, watch out for another tutorial coming soon on creating HTML emails, which are great for newsletters. If you wish to try out a demo of this tutorial, then click on the link below. Please note that the email will be sent to your own email, and not mine. It will also state that the email is from your name and your email address.

Demo Here | Source Images (not files)

 

Comments

steve says:
Posted on 06/08/2010 at 04:30am
this is a pretty good tutorial. I like that you showed the raw javascript, instead of going straight into a library, this way it actually teaches you how to do it.
nady says:
Posted on 11/08/2010 at 08:32pm
thanks a lot, btw nice captcha (* What year is it? ), if use this captcha in contact form to look great.
Posted on 07/01/2011 at 07:24pm
This is a really helpful tutorial! Thanks for sharing. Everything works wonderfuly.

Add a Comment

* Required Field

* Username:


Website:


* Comment:


* What year is it?


Back to Articles Share to Facebook Share to Twitter Stumble It More...