PHP contact form using jQuery validation

5

Hey! So, you need a PHP contact form with jQuery validation but don’t know how to build one right? No problem, i’m here to help. All you need is a server that supports php, and the client to have javascript enabled. In this tutorial we will show you how to build the contact form ( it’s a single page, yea ) and how to set it up on your server. First of all, check if your server supports the “mail()” function. You can do this by putting a simple PHP page on your server that has the fallowing code :

<?php
phpinfo();
?>

Check to see if your results has something like “sendmail”. If you find that, we’re ok, you can send e-mails via mail() function. We’re ok ? Let’s start…

Step 1 : Creating the HTML form ( page )

OK, now we have to create our html contact form page. Create a new page ( give it any name you want as long as it has the php extension ). Creating a PHP page will help us to display everything in only one page, and not have multiple ones. We also going to use a PHP constant for the action on the form. The constant will represent the url for the current filename ( relative to the document root ). This will ensure us that after pressing the send button the page is the same.

<!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 2 : Let’s color it a little bit

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 everything worked ok, the output of the page should look like the one bellow.

Contact form using php and jquery

Step 3 : Validate using JQuery

If you haven’t seen yet, we already putted this line in the HTML ( PHP ) page created above.

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

Loading JQuery alone is only the first part. We also 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. Then reference it like bellow.

<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 work. Keep in mind 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”. Bellow is an update for the form with the classes already written.

<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="" class="required" />
	</div>

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

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

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

Step 4 : 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.

<?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 = '[email protected]'; //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;
	}
}
?>

Ok, we are almost finish. All we have to do is insert a little more PHP code to output two kinds of messages. The first message is to notify us in case there were errors or any other problems after the submission, and the other is a message to tell us that the email was sent and there were no problems. 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 class="error">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 } ?>

We are now done :)

You just 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 you are ready to go!. If you enjoyed the tutorial, please share it with others using the icons bellow. And if you want to congratulate me, post a comment, send me a beer ( via e-mail ) or anything you have in mind. Before we finish, I’ve putted the full code bellow. Regards…

<?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 = '[email protected]'; //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 class="error">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="" class="required" />
		</div>

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

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

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

5 Responses

  1. Interesting article. Were did you got all the information from… :)

  2. HP says:

    Very good example. One question: what if one field is not required/optional. What changes would be needed in the PHP?

  3. admin says:

    You simply remove the [class="required"] tag from the input :)

  4. Coder says:

    Hi there, thanks for the tutorial, really nice!
    However, have you checked the finished code?

    It has errors:
    ‘ . “\r\n” . ‘Reply-To: ‘ . $email; mail($emailTo, $subject, $body, $headers); $emailSent = true; } } ?>

    That code above sits on top of the form when finished and viewed? Missing some code in the top part of the PHP code? What would you recommend?

© 2014 webozaurus.com. All rights reserved.
Seo tools, programming, icons and more...