Advanced jQuery contact form with php support

Simplex Ajax Contact Form Pro

In this modern era, most websites are using jQuery and ajax in their forms to enhance user experience.
In today’s tutorial, I am going to build an advanced php contact form with the help of Ajax and jQuery. This contact form can have the ability to send mail to user selected address from multiple email addresses. For example, if a business has multiple departments, then people can able to select a particular department they want to contact and the mail will go to the email address that corresponds to the selected department.
And interestingly, this contact form could work in both situations when javascript is enabled or disabled without any visual change between them except a page refresh.

Update(26 Dec 2011): Spam Protection added
Many people asking me how to add a spam protection for this contact form. In this update, I’ve included a simple math guard protection by Codegravity.com. Thanks for Codegravity
for the awesome spam protection code.

Download the ClassMathGuard.php class file from http://www.phpclasses.org/package/3926-PHP-CAPTCHA-validation-using-math-expressions.html and paste it inside the folder where you have the contact.php file.
Paste this php function just above the submit button code or paste it where you want the MathGuard question to show in the form.

<?php MathGuard::insertQuestion(); ?>

Also i’ve updated in the code $_REQUEST to $_POST for better protection.
I’ve updated my full php code below to include the MathGuard protection. Also you can download the updated source file below.

 

Advanced jquery ajax contact-form

Basic HTML form

First, we will look in to building the html form. All the html elements should go in to contact.php


 

Contact Form

< ?php if($result) echo ”

“.$result.”

“; ?>

<?php MathGuard::insertQuestion(); ?>

The first input of the form that I have included is a select box with 3 options namely sales, support and billing. Each option can have a unique email address which I will set it later in the php part, so the email will be sent to the email address corresponding to the selected option. The remaining inputs are commonly used in most contact forms and the last one is a checkbox to let the visitor to have themselves a copy of the sending email. There is one more input with type hidden. This input will determine whether or not the javascript is enabled in the client’s browser. What is the actual plan? We will set the hidden field’s value as “false” by default and alter it later with the use of javascript. So that way if the hidden field is unchanged, then we know that javascript is not enabled. I forget to tell you about the div with ID “result” that you might noticed in the start of the form. I have used this div to print out all the php validation result.

Styling with CSS

Now we will write some css code to style up our form and save it as contact.css.

body { 
	background:#999;
}

#contactform { 
	width:400px; 
	margin:50px auto; 
	background:#fff; 
	padding:20px; 
	-moz-border-radius:15px; 
	-webkit-border-radius:15px; 
	border-radius:15px; 
}

.form { 
	text-align:left; 
	font-size:18px; 
	font-weight:normal; 
	font-family:"Times New Roman", Times, serif; 
	color:#666;
}

h1 { 
	font-family: "Century Gothic", "Times New Roman", Times, serif; 
	font-size:28px; 
	color: #333; 
	margin-bottom:10px; 
}

h1 span {
	color: #00CC33; 
}

input.text,textarea.text, select.text { 
	width:300px; 
	border:1px solid #CCCCCC; 
	padding:5px; 
	margin-bottom:10px; 
	background: url(input-bg.gif) top left no-repeat; 
}

#result { 
	color:#FF0000;
	font-style: italic;
	margin-bottom: 5px
}

.message {
	background: #33FF99;
	padding: 5px 3px;
}

img.loading-img {
	padding: 5px 3px;
}

textarea.text { 
	height:100px;
}

input#submit { 
	padding: 5px 10px; 
	background: #f2f2f2; 
	border:1px solid #e5e5e5; 
	font-family: Georgia, "Times New Roman", Times, serif; 
	font-style: italic; 
	font-size: 18px; 
	color: #000; 
	-moz-border-radius:15px; 
	-webkit-border-radius:15px; 
	border-radius:15px; 
}

Including css file and jQuery library in the document header

Include the css file that we just created and the jQuery library in to the document header.

Alter the hidden field’s value using javascript

The above simple code will set the hidden field’s(browser_check) value as true if the javascript is enabled. Otherwise, it remains unchanged.

jQuery for form processing

For the next part, we will play with some jQuery code to process the form submission.

We will begin with writing a click function to listen to the form submission.

 $("#submit").click(function()
{
//code here 
});

Now, inside the click function, we will add a bit of code to insert a fancy loader image. This is to intimate the user that the form validation is in progress. The following code will insert an image tag inside the div ID result.

 $('#result').html('loader image').fadeIn();

The next thing I have to do is fetching the form data. To do this, I am going to use the jQuery function serialize(). What the function will do is that creates a text string in standard URL-encoded notation. The text string will look like

name=value&email=value&phno=value&subject=value&msg=value

I am initializing the text string in to the variable ‘input_data’.

 var input_data = $('#form').serialize();

Next step is adding the Ajax.

$.ajax({
type: "POST",
url:  "", //this will post the form values to the same page
data: input_data,
success: function(msg){
$('.loading-img').remove(); //Removing the loader image because the validation is finished
$('
‘).html(msg).appendTo(‘div#result’).hide().fadeIn(‘slow’); //Appending the output of the php validation in to the html div } });

Complete Javascript code

Validate the data with PHP

So we are moving to the last part, PHP validation.

The php validation code should go before the start of html code and so your entire file will look like the below structure

< ?php     //php code ?>
  //html code start
  //html form
  //javascript code
  //html code end

For the first step of validation, we need to verify that whether a POST request is actually made or not.

if($_POST)
{ 
	//all php validation code goes here
}

Get all the data sent from the form.

$javascript_enabled = trim($_POST['browser_check']);
$department = trim($_POST['dept']);
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$phno = trim($_POST['phno']);
$subject = trim($_POST['subject']);
$msg = trim($_POST['msg']);
$selfcopy = trim($_POST['selfcopy']);

//email address settings
$sales_address = "Your @sales address";
$support_address = "Your @support address";
$billing_address = "Your @billing address";
$headers = "From: ".$email;
$message = "Contact name: $name\nContact Email: $email\nContact Phone: $phno\n\nMessage: $msg";

Ok, now we need to determine the email address to where the email should go.

if ( $department == "sales") $to = $sales_address;
elseif ( $department == "support") $to = $support_address;
elseif ( $department == "billing") $to = $billing_address;

The above code will set the $to variable with the email address based on value of the $department variable.

By the following php code, we will validate the fields (name, email, phone number, subject and message).

if ( $name == "")
	{
		$result = "Name field is required";
	}
elseif (!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/", $email)) 
	{
		$result = "Enter a valid email address";
	}
elseif(!preg_match("/^[0-9]{2}-[0-9]{10}$/", $phno)) //check for a pattern of 91-0123456789
	{
		$result = "Enter a valid phone number";
	}
elseif ( $subject == "")
	{
		$result = "Subject is required";
	}
elseif ( strlen($msg) < 10 )
	{
		$result = "Write more than 10 characters";
	}

You might notice that i have validated the phone number against a pre-defined pattern (xx-xxxxxxxxxx). It is a 10 digit phone number with country code pattern. You can re-define it with your own pattern by changing the numbers between the curly braces.

Once everything is validated, we will then call the mail function. And in the next step, by verifying whether the $selfcopy variable has the value “yes”, we will send the mail to the sender by just changing the “to” parameter.

	else
	{
		mail($to, $subject, $message, $headers);
		if( $selfcopy == "yes" )
			mail($email, $subject, $message, $headers);
		$result = "Your mail has been sent succesfully!";
	}

After that

if($javascript_enabled == "true") {
		echo $result;
		die();
	}

In the above condition , if the variable $javascript_enabled is set with “true”, then the value of $result will be echoed through the jQuery function html(). Otherwise, it will be directly printed out at the line:


 

 

Complete PHP code

 

require ("ClassMathGuard.php"); //MathGuard PHP Class file
if($_POST)
{
$javascript_enabled = trim($_POST['browser_check']);
$department = trim($_POST['dept']);
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$phno = trim($_POST['phno']);
$subject = trim($_POST['subject']);
$msg = trim($_POST['msg']);
$selfcopy = trim($_POST['selfcopy']);


//mail settings
$sales_address = "Your sales address";
$support_address = "Your support address";
$billing_address = "Your billing address";
$headers = "From: ".$email;
$message = "Contact name: $name\nContact Email: $email\nContact Phone: $phno\n\nMessage: $msg";
if (MathGuard :: checkResult($_POST['mathguard_answer'], $_POST['mathguard_code'])) { 
	if ( $department == "sales") $to = $sales_address;
	elseif ( $department == "support") $to = $support_address;
	elseif ( $department == "billing") $to = $billing_address;

	if ( $name == "" )
	{
		$result = "Name field is required";
	}
	elseif (!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/", $email)) 
	{
		$result = "Enter a valid email address";
	}
	elseif(!preg_match("/^[0-9]{2}-[0-9]{10}$/", $phno)) //check for a pattern of 91-0123456789
	{
		$result = "Enter a valid phone number";
	}
	elseif ( $subject == "" )
	{
		$result = "Subject is required";
	}
	elseif ( strlen($msg) < 10 )
	{
		$result = "Write more than 10 characters";
	}
	else
	{	
		
			mail($to, $subject, $message, $headers);
		if( $selfcopy == "yes" )
			mail($email, $subject, $message, $headers);
		$result = "Your mail has been sent successfully!";
		
	}
}
else $result = "Bad Answer, Please try again!";
	
	if($javascript_enabled == "true") {
		echo $result;
		die();
	}

}

Awesome! We have finished doing our jQuery contact form with php support.

7,978 Downloads