PHP Contact Form with jQuery Validation

Posted: October 28, 2010 in CSS, HTML, jQuery, PHP
Tags: , , ,

Hi there! You need a jQuery contact form for your website but don’t know how to create one? Please read along and maybe you’ll get lucky. A contact form is very helpful in giving your visitors a way to contact you. In this tutorial, I will help you on how to create your own jQuery contact form using PHP and JQuery.

Let’s start with the basics. We only need a single page for our contact form and this page will contain the markup, PHP to process our contact form and JQuery validating. For those who need to see a working demo of the jQuery contact form.



Step One: jQuery Contact Form Markup

First, let’s create the markup for our contact form. Create a new page called contact.php (or whatever name you want as long as it has a PHP extension). Having a PHP file affords us the luxury of only having a single page to display and at the same time process our contact form. We also used a PHP constant for the action value of our contact form. That constant is the filename of the current file, relative to the document root. This is to ensure us that our form will go to the same page after sending our form.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
	<title>PHP Contact Form with JQuery Validation</title>
	<meta http-equiv="content-type" content="text/html;charset=utf-8" />
	<meta http-equiv="Content-Style-Type" content="text/css" />

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

	<style type="text/css">

	</style>
</head>

<body>
<div id="contact-wrapper">
	<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform">
		<div>
		    <label for="name"><strong>Name:</strong></label>
			<input type="text" size="50" name="contactname" id="contactname" value="" />
		</div>

		<div>
			<label for="email"><strong>Email:</strong></label>
			<input type="text" size="50" name="email" id="email" value="" />
		</div>

		<div>
			<label for="subject"><strong>Subject:</strong></label>
			<input type="text" size="50" name="subject" id="subject" value="" />
		</div>

		<div>
			<label for="message"><strong>Message:</strong></label>
			<textarea rows="5" cols="50" name="message" id="message"></textarea>
		</div>
	    <input type="submit" value="Send Message" name="submit" />
	</form>
</div>
</body>
</html>

Step Two: Give it some style
We’re going to apply some styling to our contact form using CSS to make it more interesting. For the purposes of this tutorial we’re going to embed our CSS right inside contact.php inside the head section and in between the style tags.

body {
	font-family:Arial, Tahoma, sans-serif;
}
#contact-wrapper {
	width:430px;
	border:1px solid #e2e2e2;
	background:#f1f1f1;
	padding:20px;
}
#contact-wrapper div {
	clear:both;
	margin:1em 0;
}
#contact-wrapper label {
	display:block;
	float:none;
	font-size:16px;
	width:auto;
}
form#contactform input {
	border-color:#B7B7B7 #E8E8E8 #E8E8E8 #B7B7B7;
	border-style:solid;
	border-width:1px;
	padding:5px;
	font-size:16px;
	color:#333;
}
form#contactform textarea {
	font-family:Arial, Tahoma, Helvetica, sans-serif;
	font-size:100%;
	padding:0.6em 0.5em 0.7em;
	border-color:#B7B7B7 #E8E8E8 #E8E8E8 #B7B7B7;
	border-style:solid;
	border-width:1px;
}

If you’re following along, your contact form should look like this:


Step Three: Validate using JQuery
We already loaded JQuery in case you haven’t noticed in our initial contact form markup:

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

Loading JQuery alone only gets half of the job done. We still need a JQuery plugin called Validation to
help us validate our contact form.After you’ve downloaded and extracted the plugin, look for
jquery.validate.pack.js
file and save it where your contact.php is saved andreference it from the
file just like what you did with JQuery.

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

Now we need to initialize the JQuery:Validation plugin in order to use it. Take note that
 #contactform is the id value of the form.

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

<script type="text/javascript">
$(document).ready(function(){
	$("#contactform").validate();
});
</script>

After that, we now need to add a class attribute to our input fields. If you just need a required
field you just add class=”required” to the input tag and when you need to require and validate an
email so that the format is correct then you need to add class=”required email”. Here’s the
updated markup for our jQuery contact form with the classes already added.

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform">
	<div>
	    <label for="name"><strong>Name:</strong></label>
		<input type="text" size="50" name="contactname" id="contactname" value="" />
	</div>

	<div>
		<label for="email"><strong>Email:</strong></label>
		<input type="text" size="50" name="email" id="email" value="" />
	</div>

	<div>
		<label for="subject"><strong>Subject:</strong></label>
		<input type="text" size="50" name="subject" id="subject" value="" />
	</div>

	<div>
		<label for="message"><strong>Message:</strong></label>
		<textarea rows="5" cols="50" name="message" id="message"></textarea>
	</div>
    <input type="submit" value="Send Message" name="submit" />
</form>

Now refresh your jQuery contact page and submit the contact form without entering
any data. Your contact page will catch the errors and hopefully will look like
the image below. Also try entering a different format for the email field and you
should see a different message. Try reading the Validation documentation for more
validation options.


Step Four: Submit and process the form using PHP
Now it’s time to add some PHP magic to our jQuery contact form! Place this code on
the topmost section of your file (just above your DOCTYPE declaration). You might
be wondering why we need to validate the inputs again even if we already validated
the inputs using Javascript. The reason is that PHP will act as our second level
of validation in case Javascript is turned off on the client’s machine. I highly
suggest that you don’t rely on Javascript alone for validating form inputs. Aside
from validating inputs, PHP will also be responsible for sending out the email in
case no errors were found.

I’ve stripped down and borrowed the code below from this very helpful article.
The green comments should basically explain what each code snippet is doing.

<?php
//If the form is submitted
if(isset($_POST['submit'])) {

	//Check to make sure that the name field is not empty
	if(trim($_POST['contactname']) == '') {
		$hasError = true;
	} else {
		$name = trim($_POST['contactname']);
	}

	//Check to make sure that the subject field is not empty
	if(trim($_POST['subject']) == '') {
		$hasError = true;
	} else {
		$subject = trim($_POST['subject']);
	}

	//Check to make sure sure that a valid email address is submitted
	if(trim($_POST['email']) == '')  {
		$hasError = true;
	} else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
		$hasError = true;
	} else {
		$email = trim($_POST['email']);
	}

	//Check to make sure comments were entered
	if(trim($_POST['message']) == '') {
		$hasError = true;
	} else {
		if(function_exists('stripslashes')) {
			$comments = stripslashes(trim($_POST['message']));
		} else {
			$comments = trim($_POST['message']);
		}
	}

	//If there is no error, send the email
	if(!isset($hasError)) {
		$emailTo = 'youremail@yoursite.com'; //Put your own email address here
		$body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nComments:\n $comments";
		$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;

		mail($emailTo, $subject, $body, $headers);
		$emailSent = true;
	}
}
?>

We’re almost finished! All we have to do is insert a little more PHP to output two
kinds of messages. The first message is to notify us in case there were errors
after our submission, and the other is a message to tell us that the email was
already sent and no errors were found. The code for that will just sit right
inside the contact-wrapper div but right before the jQuery contact form markup.

<?php if(isset($hasError)) { //If errors are found ?>
	<p>Please check if you've filled all the fields with valid information. Thank you.</p>
<?php } ?>

<?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?>
	<p><strong>Email Successfully Sent!</strong></p>
	<p>Thank you <strong><?php echo $name;?></strong> for using my contact form! Your email was successfully sent and I will be in touch with you soon.</p>
<?php } ?>


Finished Code:

<?php
//If the form is submitted
if(isset($_POST['submit'])) {

	//Check to make sure that the name field is not empty
	if(trim($_POST['contactname']) == '') {
		$hasError = true;
	} else {
		$name = trim($_POST['contactname']);
	}

	//Check to make sure that the subject field is not empty
	if(trim($_POST['subject']) == '') {
		$hasError = true;
	} else {
		$subject = trim($_POST['subject']);
	}

	//Check to make sure sure that a valid email address is submitted
	if(trim($_POST['email']) == '')  {
		$hasError = true;
	} else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
		$hasError = true;
	} else {
		$email = trim($_POST['email']);
	}

	//Check to make sure comments were entered
	if(trim($_POST['message']) == '') {
		$hasError = true;
	} else {
		if(function_exists('stripslashes')) {
			$comments = stripslashes(trim($_POST['message']));
		} else {
			$comments = trim($_POST['message']);
		}
	}

	//If there is no error, send the email
	if(!isset($hasError)) {
		$emailTo = 'youremail@yoursite.com'; //Put your own email address here
		$body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nComments:\n $comments";
		$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;

		mail($emailTo, $subject, $body, $headers);
		$emailSent = true;
	}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
	<title>PHP Contact Form with JQuery Validation</title>
	<meta http-equiv="content-type" content="text/html;charset=utf-8" />
	<meta http-equiv="Content-Style-Type" content="text/css" />

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

<script type="text/javascript">
$(document).ready(function(){
	$("#contactform").validate();
});
</script>

<style type="text/css">
body {
	font-family:Arial, Tahoma, sans-serif;
}
#contact-wrapper {
	width:430px;
	border:1px solid #e2e2e2;
	background:#f1f1f1;
	padding:20px;
}
#contact-wrapper div {
	clear:both;
	margin:1em 0;
}
#contact-wrapper label {
	display:block;
	float:none;
	font-size:16px;
	width:auto;
}
form#contactform input {
	border-color:#B7B7B7 #E8E8E8 #E8E8E8 #B7B7B7;
	border-style:solid;
	border-width:1px;
	padding:5px;
	font-size:16px;
	color:#333;
}
form#contactform textarea {
	font-family:Arial, Tahoma, Helvetica, sans-serif;
	font-size:100%;
	padding:0.6em 0.5em 0.7em;
	border-color:#B7B7B7 #E8E8E8 #E8E8E8 #B7B7B7;
	border-style:solid;
	border-width:1px;
}
</style>
</head>

<body>
	<div id="contact-wrapper">

	<?php if(isset($hasError)) { //If errors are found ?>
		<p>Please check if you've filled all the fields with valid information. Thank you.</p>
	<?php } ?>

	<?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?>
		<p><strong>Email Successfully Sent!</strong></p>
		<p>Thank you <strong><?php echo $name;?></strong> for using my contact form! Your email was successfully sent and I will be in touch with you soon.</p>
	<?php } ?>

	<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform">
		<div>
		    <label for="name"><strong>Name:</strong></label>
			<input type="text" size="50" name="contactname" id="contactname" value="" />
		</div>

		<div>
			<label for="email"><strong>Email:</strong></label>
			<input type="text" size="50" name="email" id="email" value="" />
		</div>

		<div>
			<label for="subject"><strong>Subject:</strong></label>
			<input type="text" size="50" name="subject" id="subject" value="" />
		</div>

		<div>
			<label for="message"><strong>Message:</strong></label>
			<textarea rows="5" cols="50" name="message" id="message"></textarea>
		</div>
	    <input type="submit" value="Send Message" name="submit" />
	</form>
	</div>
</body>
</html>

We are Done!
You have created a jQuery contact form using PHP and JQuery for
validation all contained in a single page! All you have to do is
put your email address in line 41 and off you go! Great job! I
hope you will find this tutorial helpful as I’ve carefully
detailed all the steps needed to create our contact form.
Please tell me what you think and I would appreciate your
comment. Thank you so much for reading and hope to see you again.

Advertisements
Comments
  1. TwitterRight says:

    How to Stay In Touch With Your Blog’s Community – WP Contact Form with Captcha…

    Just read your posting and found it very interesting. I’ve added a Trackback to it on my weblog Have a great day and thanks again:)…

  2. codehunterbd says:

    @TwitterRight,Welcome.Thanks to read my blog.

  3. codebutcher says:

    Thanks for the tutorial. One thing – ereg is depreciated in php5 and will be gone in php6. Better to use preg_match in your code.

  4. BellDelo says:

    I have the same opinion with most of your points, but some need to be discussed further, I will hold a small talk with my partners and perhaps I will look for you some suggestion later.

    – Henry

  5. Llano says:

    I have a problem with the overall premise of your article but I still think its really informative. I really like your other posts. Keep up the great work. If you can add more video and pictures can be much better. Because they help much clear understanding. 🙂 thanks Llano.

  6. huge units says:

    Thanks buddy. Not bad site you have here. Have some extra sites to point to with more info?

  7. Tafeannuavag says:

    Вскрытие замков дверей в Москве в районе Филёвский Парк 24 часа в сутки.Правильные мастера вскроют замки всех марок без повреждения железных сейфов.Наш сайт: http://www.vskritieremont.ru/
    Срочное вскрытие замков металических дверей в центре в районе Покровское-Стрешнево

  8. A nice and a very informative blog! I am so glad I stumbled your page. Keep up the extrordinary work. Have a great day!mail forwarder

  9. Richard says:

    Heya i’m for the primary time here. I came across this board and I find It truly helpful & it helped me out a lot. I hope to give something back and help others such as you aided me.

  10. Does your website have a contact page? I’m having trouble locating it but, I’d like to shoot you an e-mail.

    I’ve got some ideas for your blog you might be interested in hearing. Either way, great site and I look forward to seeing it develop over time.

  11. Howdy! I know this is kinda off topic however I’d figured I’d ask.
    Would you be interested in exchanging links or maybe guest authoring a blog article
    or vice-versa? My blog covers a lot of the same topics as yours
    and I believe we could greatly benefit from each other.
    If you happen to be interested feel free to send me an email.
    I look forward to hearing from you! Awesome blog
    by the way!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s