AJAX Contact Form with Realtime Validator – Powered by JavaScript and PHP
Posted on September 2, 2008, Filled under AJAX, PHP, jQuery,
Bookmark it


The aim of this tutorial is to help you to create a simple (tableless) contact form using AJAX, JQuery & PHP. We will have a HTML page which will contain the form, a CSS file, a php page where the data will be sent and another file where the validation function(s) will be located. JQuery is a new and powerful library which simplifies the way that you write JavaScript.
Step 1 – Creating the configuration file
config.php
<?php
// To
define("WEBMASTER_EMAIL", 'your_name@domain.com');
?>Here you should fill the e-mail address where you wish to receive the mail as well as the address where you wish to receive the replies (usually the same).
Step 2 – Creating the css file
style.css
/*
Credits: Bit Repository
CSS Library: http://www.bitrepository.com/
*/
html, body { padding: 0; border: 0px none; }
.notification_error
{
border: 1px solid #A25965;
height: auto;
width: 90%;
padding: 4px;
background: #F8F0F1;
text-align: left;
-moz-border-radius: 5px;
}
.notification_ok
{
border: 1px #567397 solid;
height: auto;
width: 90%
padding: 8px;
background: #f5f9fd;
text-align: center;
-moz-border-radius: 5px;
}
.info_fieldset { -moz-border-radius: 7px; border: 1px #dddddd solid; }
.info_fieldset legend
{
border: 1px #dddddd solid;
color: black;
font: 13px Verdana;
padding: 2px 5px 2px 5px;
-moz-border-radius: 3px;
}
.button
{
border: 1px solid #999999;
border-top-color: #CCCCCC;
border-left-color: #CCCCCC;
background: white;
color: #333333;
font: 11px Verdana, Helvetica, Arial, sans-serif;
-moz-border-radius: 3px;
}
/* Label */
label {width: 140px; padding-left: 20px; margin: 5px; float: left; text-align: left;}
/* Input, Textarea */
input, textarea
{
margin: 5px;
padding: 0px;
float: left;
border: 1px solid #999999;
border-top-color: #CCCCCC;
border-left-color: #CCCCCC;
color: #333333;
font: 11px Verdana, Helvetica, Arial, sans-serif;
-moz-border-radius: 3px;
}
/* BR */
br { clear: left; }Step 3 – Creating the html contact page
This is the page where the AJAX call to contact.php is made. I will explain you the JavaScript Code in detail below:
contact.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>TableLess Ajax Contact Form (Demo)</TITLE>
<meta name="Keywords" content="form, divs">
<meta name="Description" content="A CSS Tableless Ajax Contact Form">
<!-- JQuery -->
<script type="text/javascript" src="jquery-1.2.6.min.js"></script>
<script type="text/javascript">
// we will add our javascript code here
$(document).ready(function(){
$("#ajax-contact-form").submit(function(){
// 'this' refers to the current submitted form
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "contact.php",
data: str,
success: function(msg){
$("#note").ajaxComplete(function(event, request, settings){
if(msg == 'OK') // Message Sent? Show the 'Thank You' message and hide the form
{
result = '<div class="notification_ok">Your message has been sent. Thank you!</div>';
$("#fields").hide();
}
else
{
result = msg;
}
$(this).html(result);
});
}
});
return false;
});
});
</script>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<center>
<center><h3>A Tableless Contact Form (JQuery & AJAX)</h3></center>
<div align="left" style="width: 500px;">
<fieldset class="info_fieldset"><legend>Contact</legend>
<div id="note"></div>
<div id="fields">
<form id="ajax-contact-form" action="javascript:alert('success!');">
<label>Name</label><INPUT class="textbox" type="text" name="name" value=""><br />
<label>E-Mail</label><INPUT class="textbox" type="text" name="email" value=""><br />
<label>Subject</label><INPUT class="textbox" type="text" name="subject" value=""><br />
<label>Comments</label><TEXTAREA class="textbox" NAME="message" ROWS="5" COLS="25"></TEXTAREA><br />
<label> </label><INPUT class="button" type="submit" name="submit" value="Send Message">
</form>
</div>
</fieldset>
</div>
</center>
</body>
</html>
Once the DOM is loaded (we determine this by using $(document).ready()), the script checks if the user submitted the form by using $(“form”).submit(). If it is, the form elements (names & values) are serialized in order to pass them to the AJAX Call:
var str = $("form").serialize();$.ajax() takes one argument, an object of key/value pairs, that are used to initalize and handle the request, and returns the XMLHttpRequest object for post-processing (like manual aborting) if needed.
Some options are used to control the behaviour of $.ajax. The information is from JQuery Documentation:
(String) type – This is to determine the type of request that is made: ‘POST’ or ‘GET’. (default is ‘GET’)
(String) url – The URL to request
(Object|String) data – Data to be sent to the server. It is converted to a query string, if not already a string. Is appended to the url for GET-requests. See processData option to prevent this automatic processing.
(Function) success – A function to be called if the request succeeds. The function gets passed one argument: The data returned from the server, formatted according to the ‘dataType’ parameter.
To find out more about $.ajax consider visiting http://docs.jquery.com/API/1.1/AJAX.
The request succeded? In this case we will call the ajaxComplete(callback) function, which executes whenever an AJAX request is completed. The XMLHttpRequest and settings used for that request are passed as arguments to the callback.
If ‘OK’ is returned the form hides and a thank you message is shown. Otherwise, the script will show the errors.
$.ajax({
type: "POST",
url: "contact.php",
data: str,
success: function(msg){
$("#note").ajaxComplete(function(event, request, settings){
if(msg == 'OK') // Message Sent? Show the 'Thank You' message and hide the form
{
result = '<div class="notification_ok">Your message has been sent. Thank you!</div>';
$("#fields").hide();
}
else
{
result = msg;
}
$(this).html(result);
});
}
});
In the next page of our tutorial we will create: functions.php (which has the e-mail address validator) and contact.php (which is the script that parses the submitted data).
Step 4 – Creating the functions’ script.
functions.php
<?php
function ValidateEmail($email)
{
/*
(Name) Letters, Numbers, Dots, Hyphens and Underscores
(@ sign)
(Domain) (with possible subdomain(s) ).
Contains only letters, numbers, dots and hyphens (up to 255 characters)
(. sign)
(Extension) Letters only (up to 10 (can be increased in the future) characters)
*/
$regex = '/([a-z0-9_.-]+)'. # name
'@'. # at
'([a-z0-9.-]+){1,255}'. # domain & possibly subdomains
'.'. # period
"([a-z]+){2,10}/i"; # domain extension
if($email == '') {
return false;
}
else {
$eregi = preg_replace($regex, '', $email);
}
return empty($eregi) ? true : false;
}
?>This file contains only the e-mail address validator, in our sample, but you can use it to add more (validation) functions which can be used in the contact.php page.
Step 5 – Creating the page which parses the data
contact.php
<?php
/*
Credits: Bit Repository
URL: http://www.bitrepository.com/a-simple-ajax-contact-form-with-php-validation.html
*/
include 'config.php';
error_reporting (E_ALL ^ E_NOTICE);
$post = (!empty($_POST)) ? true : false;
if($post)
{
include 'functions.php';
$name = stripslashes($_POST['name']);
$email = $_POST['email'];
$subject = stripslashes($_POST['subject']);
$message = stripslashes($_POST['message']);
$error = '';
// Check name
if(!$name)
{
$error .= 'Please enter your name.';
}
// Check email
if(!$email)
{
$error .= 'Please enter an e-mail address.';
}
if($email && !ValidateEmail($email))
{
$error .= 'Please enter a valid e-mail address.';
}
// Check message (length)
if(!$message || strlen($message) < 15)
{
$error .= "Please enter your message. It should have at least 15 characters.";
}
if(!$error)
{
$mail = mail(WEBMASTER_EMAIL, $subject, $message,
"From: ".$name." <".$email.">rn"
."Reply-To: ".$email."rn"
."X-Mailer: PHP/" . phpversion());
if($mail)
{
echo 'OK';
}
}
else
{
echo '<div class="notification_error">'.$error.'</div>';
}
}
?>In contact.php, we have to determine first if a POST request was sent to the file. If $post is not null, the functions.php file is included (containing the e-mail validator) and the POST fields are declared. Each required field is checked. If any error is found, the $error variable will be filled with that error message. At the end, if $error is null (as it was initially) & the mail is sent, contact.php will output ‘OK’ (which is checked in contact.html). It is is not null, contact.php will output the error(s), which will be shown, of course, in contact.html.
Select the type of item you would like to download:
- September 2, 2008
- article by Gabriel C.
- 305 comments




305 Replies to "AJAX Contact Form with Realtime Validator – Powered by JavaScript and PHP"
August 6, 2010 at 7:55 AM
Hello Gabriel, I have been using (possibly) an earlier version of your form (w/o the captcha) and it works awesomely! I’ve modified it quite extensively to send html in emails, used it inside Colorbox, etc. I am now try to modify it again but I am stuck on this. I want be able to add red outlines to required fields inside my form upon error checking. I figured I would have to assign specific variables to each field and have them echo out if there are empty fields like so:
if(!$name) {
$name_error = 'do something';
}
but I am new to AJAX and but I realize that all messages are being passed into the “note” div with the AJAX. Can you advise as to go about adding a class “error” to the “required” form elements or point me in a direction where I might be able to figure this out? Would be greatly appreciated.
Thanks again for a great script!
August 16, 2010 at 9:51 AM
Awesome tut,
Cheers dude.
August 17, 2010 at 1:38 PM
Gabriel, you are the man!
I can’t believe it, how can you be replying for more than 2 years?
The code is perfect, just some minors errors on validator w3c that i could solve well.
I don’t have problems, only one question.
I was thinking to build a select list of contact, e.g:
To: Admin
Moderator
ect.
BUT, for each contact i would like to give a diferent email address. eg. admin@domain.ro, moderator@domain.ro…
How can I do that? I read every post and i didn’t see that.
Большой спасибо брат
August 26, 2010 at 8:19 AM
hello, any idea how to do it?
thanks
August 19, 2010 at 7:27 PM
I keep getting this error when I test my submit button:
Warning: mail() [function.mail]: SMTP server response: 504 5.5.2 : Helo command rejected: need fully-qualified hostname in C:\sites\single16\oldieolga\webroot\medellin\contact.php on line 56
–
Line 56 is:
$mail = mail(WEBMASTER_EMAIL, $subject, $message,
“From: “.$name.” rn”
.”Reply-To: “.$email.”rn”
.”X-Mailer: PHP/” . phpversion());
if($mail)
Not sure what the problem is??
August 25, 2010 at 1:15 AM
Hey,
I wanted to know how to make this into SMTP method, cuz my server filters a lot of mails coming through phpmail!