AJAX Form with CAPTCHA, Realtime Validation and PHP Backend
Create Unlimited Secure Forms with AJAX Form Pro * now with Control Panel
This is a professional multi-usage AJAX Form Builder meant to enhance the functionality of your website by providing an interactive user experience for your readers that need to reach you, whether they need to send a feedback, share their opinion regarding your website, fill a survey, leave a testimonial or even make a room reservation online.

Beside the premium AJAX Form, I would like to offer you a short tutorial regarding the creation of a basic AJAX Contact Form. It will give you an idea of how you can create similar web applications using jQuery and AJAX.
The aim of the tutorial is to help you to create a simple (tableless) ajax 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.
I recommend you using the Firefox Extension Firebug, a popular and powerful web development tool. It adds a global variable named “console” to all web pages loaded in Firefox. This object contains many methods that allow you to write to the Firebug console to expose information that is flowing through your scripts. While executing AJAX Code you can check the console to see how the data is sent to the remote files, in this case parse.php.

If ‘OK’ is returned the form hides and a thank you message is shown. If any other text is shown (beside ‘OK’), then there are errors and they will be shown above the form.
$.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.
Get Basic (Limited)
This version contains the basic features that were discussed in the tutorial.
Get Premium (Professional)
This is a professional Multi-usage AJAX (Contact) Form with lots of features and support for all form elements.
The script can be practically used to create any type of form that collects data and sends it to your email inbox including but not limited to:
- Contact/Feedback Form
- Support Form
- Customer Survey Form
- Online Product Order Form
- Event Registration Form
- Employment Form
- Make a Room Reservation Online Form
- Send Testimonial Form
- Subscribe to Newsletter Form
- Gift Order Form
Some of the features you get with AJAX Form Builder
Additional features include:
- 3 Layouts Available: 'Left' and 'Right' Justified Horizontal Labels, Vertical Labels, In-Field Labels (for Developer and Extended Licenses)
- The e-mail templates (message, subject) are customizable
- The errors and the notifications can be easily changed
- The script works in conjunction with other libraries beside jQuery such as MooTools or Prototype
- Set a custom subject for the mail that you receive if the subject field is removed
- "Send me a copy of the mail" feature: if activated, the user receives exactly the same mail as you get.
Server Requirements
- PHP5+
- GD Library Enabled (only if you want to use the Anti-Spam Image)
Browser Compatibility
- This script is compatible with all major browsers.
- It was tested in FireFox 3.5, IE 6, IE 7 & IE 8, Google Chrome 3.0, Opera 10, Safari 4.0, SeaMonkey 2.0, Flock 2.5.6
Is AJAX Form Pro the right script for me?
- This product is aimed to:
- Webmasters that want to improve the contact forms from their website(s)
- Web Developers that have multiple websites and need to install (contact) forms on them
- Freelance Web Developers that are looking to create interactive forms for their client(s) / website(s) / project(s)
- AJAX Form Pro is a PHP tool to build interactive forms, not just a basic Contact Form nor a WYSIWYG application.
Money Back Risk Free Trial
- I offer a 60 days money back guarantee.
- If for any reason you are not satisfied with this script you can request a refund and I will buy the script back from you. No questions asked!
- Licenses are lifetime
- Customer Support is offered within 24 hours
- Payments are processed through PayPal or 2Checkout
- Digital delivery is provided by E-Junkie
Customer Testimonials
"Very nice! We went through 8 different scripts, only to be frustrated with broken code, links, and tutorials, to finally find one so simple, beautiful and it works! We are avid PHP programmers, but are not yet too versed with AJAX, so this solution was perfect! Thanks" -
"I had a real need for a clean and stylish contact form. I tried some 11 forms before I decided on one. I have to say your form was the winning choice hands down." -
"It works very good and it solved the problem of needing a form validation as well a as a success message in the same page." -
"I am working a project for patisserie web site in Turkey and i used your form form this web site contact page. Belong to me, your form is very useful and successful, thanks a lot." -
- September 2, 2008
- article by Gabriel C.
- 547 comments


547 Replies to "AJAX Form with CAPTCHA, Realtime Validation and PHP Backend"
September 16, 2008 at 6:15 AM
a working demo would be nice
September 22, 2008 at 4:10 AM
Yes, it would be, but the script has the mail() function which can be used abusively (i.e. SPAM). If a demo will be made, it must have some protection.
September 29, 2008 at 1:24 PM
A demo is now available.
October 9, 2008 at 9:47 PM
Thank you very much for your Tutorial. But it has a small Validation error in e-mail field.
info@yahoo,com
i mention comma in the above Email address.. But it doesent validate your code..
plz check and correct it..
Thank you
October 10, 2008 at 4:02 AM
Thanks for noticing. I’ve fixed the error by adding a backslash before the period sign.
October 23, 2008 at 8:18 AM
hi, I tried it but it doesn’t work with ie6
October 23, 2008 at 8:26 AM
sorry, I forgot to put my phpserver on,
it’s working well with ie6
October 23, 2008 at 8:31 AM
Good, I was quite surprised when I read your first comment, because I know that JQuery is compatible with IE6.
October 25, 2008 at 8:28 AM
[...] Tableless Ajax Contact Form With jQuery (Tutorial & Files) – Demo [...]
October 26, 2008 at 9:04 AM
[...] Tableless Ajax Contact Form With jQuery | Demo [...]
October 28, 2008 at 7:48 PM
How might I get this to put the user’s email into the “from” field properly so that a REPLY goes back to them instead of to me? In my use, this would be considerably more useful. I’ve tried putting $from and $email into the config file, but that doesn’t do it. I don’t know enough about PHP yet.
October 29, 2008 at 4:06 AM
Replace
from line 54
with
I’ve also updated the post.
November 3, 2008 at 9:53 PM
Hi,
Awesome site, thanks so much!
I’m using your script for an email sign up form. How would I go about forcing an email subject when the user doesn’t have the option of entering a subject.
Thank you so much :)
November 4, 2008 at 3:27 AM
If you don’t need a subject from the person filling the form & want to set a specific subject you can do the following:
1. Remove line 76 from the form (the one with the subject)
2. Remove line 19 from contact.php
3. Change $subject from line 58 (where you have the mail function) with ‘your subject here’.
November 6, 2008 at 12:30 AM
thanks
November 6, 2008 at 7:09 AM
hi webmaster, i have downloaded your script but its not working
nothing is happening when i click on submit button
iam using php4 and testing under localhost do i need to change any code if any please post me
thank u
November 6, 2008 at 7:22 AM
What browser are you using (type & version)? Please take a look at this page: http://docs.jquery.com/Browser_Compatibility. Perhaps there’s a compatibility problem between JQuery & your browser. Did you see the demo in action before downloading the files?
November 8, 2008 at 5:59 PM
Great! That modification worked without a problem.
Now, I’d like for the person’s name to be put in the From: field properly. They’re typing their name into the form, but I don’t receive it. I did replace $from with $name (I forget where) and it puts it into the proper field… but, it appends @mydomain.com after it. Other than that, this script does exactly what I needed with a minimum of hassle. Thanks a lot!
November 8, 2008 at 6:18 PM
I’ve update the tutorial. Check line 53 from the contact.php page ;)
November 11, 2008 at 9:27 PM
Hi,
This is great website, keep it up :)
I’m just wondering how I would go ahead and force a sentence such as “The following email would like to sign up to the Newsletter” in the body of an email?
Also is it possible to have a checkbox submit a true or false?
Starting to get more in PHP coding… sites like theses are a great help. If there’s anyway I can donate some money for your help, please let me know :)
Thanks.
November 12, 2008 at 5:21 AM
Hi,
Thank you for your comments regarding this website. Let’s add the checkbox first.
1. Here’s the code that should be inserted in contact.html:
I recommend you to add it just AFTER:
2. Now, we have to edit contact.php. AFTER:
add the following line:
3. We will make the final modifications.
Look for:
$mail = mail(WEBMASTER_EMAIL, $subject, $message, "From: ".$name." <".$email.">\r\n" ."Reply-To: ".$email."\r\n" ."X-Mailer: PHP/" . phpversion());Just BEFORE it add the following code:
if($newsletter_signup) { $message .= "\n\n"."[The following email would like to sign up to the Newsletter.]"; }Notice how I used the string concatenation to add additional text to the message.
I hope you will manage to successfully implement the code I gave you. If you have any questions, let me know.
If you’d like to make a donation, you can look for a PayPal button located just above the pagination links for this tutorial.
November 15, 2008 at 11:14 AM
Thank you for this great form.
How would you change the submit button so when a user clicks on it, it changes to something like ‘Submitting Form, please wait…” With the dots animated.
November 15, 2008 at 11:55 AM
This form submits fast enough and a loader (until you the script gets a response from ‘contact.php’) is not really needed. However, it can be useful if the user has a slow bandwidth connection. Here’s how you can add one:
1. AFTER:
ADD the following div:
2. AFTER:
$("form").submit(function(){ADD the following code:
$("#submit").hide(); $("#loading").html('Loading...');This way the submit button is hided and the loader is shown.
3. BEFORE:
ADD:
$("#loading").hide(); $("#submit").show();The loader is hided and the submit button is restored.
As for the dots you can use an animated GIF:
$("#loading").html('Submitting Form, please wait <img src="path/to/dots.gif" align="absmiddle">');November 18, 2008 at 3:52 PM
Thank you, works great!
November 28, 2008 at 9:54 AM
Sure, here’s what you have to do:
1. Replace the following line from the contact.html page:
WITH this code::
2. Now, you have to edit contact.php. Find this line:
Replace it with:
Find:
if(!$error) {AFTER it, ADD:
3. Let’s add some validation to the new fields! Find:
// Check name if(!$name) { $error .= 'Please enter your name.'; }Replace it with:
// Check first name if(!$first_name) { $error .= 'Please enter your first name.'; } // Check last name if(!$last_name) { $error .= 'Please enter your last name.'; } // Check company if(!$company) { $error .= 'Please enter your company name.'; }To make a field optional, remove the conditional IF that verifies it.
November 28, 2008 at 4:32 AM
Great tutorial! I was wondering if i could send additional information to the email, for example i have a field called “Company” and would like it to be in front of the subject (along with the first- and last name).
November 28, 2008 at 4:44 AM
Do you want to replace the “name” field with 2 fields (first & last name) and to add an additional field called “company”? Would the subject be something like: “Company Name: First Name, Last Name”?
November 28, 2008 at 8:06 AM
Yes that’s exactly what i need. Do you know how to do this?
November 28, 2008 at 12:37 PM
Thanks so much! Once again, great tutorial. And the support is awesome :)
December 17, 2008 at 10:38 AM
It doesn’t validate for sub-domain email addresses.
Like my email address:
beyblade[- at -]quickcms [- dot -]exofire[- dot -]net
December 17, 2008 at 11:41 AM
It does now ;-) Thanks for the tip!
December 17, 2008 at 9:17 PM
Hi,
I just tried it on my website and it seems to be working fine but I am not getting any email :( I have been waiting for the last 30 minutes now. I added my email twice in the config file, is there anyplace else where I need to add it? I had to copy paste the codes into files because my zip extractor wont open the zipped file downloaded from here either :(
December 17, 2008 at 9:43 PM
For some reason when I am using this on my site, when I press ‘Submit’, js alert window comes up saying ‘success!’. But doesn’t do anything after. Also if I remove the [HTML STRIPPED] line it still does nothing.
December 17, 2008 at 9:57 PM
Oh please disregard the earlier message. I got the email after an hour! Thank you so much for this awesome script!!
December 18, 2008 at 2:22 AM
@Travis O'Donnell: After checking the contact form that you installed in your site, I've noticed that jquery-1.2.6.js is not loaded. Are you sure the file is in the main root of your site? I've tried to open it but I got an error.
August 15, 2009 at 4:59 PM
@Gabriel,
Im having the same problem. even without anything type in the form, when I click submit a window pops up with “success” nothing is validated or nothing, no error messages…
Plz help
August 15, 2009 at 10:49 PM
@anthony, this issue was already discussed. As I mentioned before, you just did not do something right (the JQuery library is not included, the ID of the form is not the right one etc.). Just check the older comments and hopefully you will find the answer. If you want to me setup the form on your website I would do it if you are willing to pay a fee.
December 23, 2008 at 7:30 AM
Thanks for helping me earlier on with the subject field. I was wondering how i could send a overview of all the fields in the email, like:
- Company:
- First name:
- Last name:
Hope you can help me out with this one!
Greetz,
Jasper
December 26, 2008 at 3:29 PM
You need to modify $message. Example:
$message = "- Company". $company."\n- First name: ".$first_name."\n- Last name: ".$last_name."\n\n".$message;
August 23, 2009 at 7:07 AM
Which file do we edit this on? contact.php or feedback.php?
That string ” $message ” exists in many spots in different files.
Thanks much for your help!
August 24, 2009 at 1:30 AM
In contact.php: add the code after
if(!$error) {(just before the mail() function is called). The file feedback.php was just used for demo purposes to demonstrate how you can add more AJAX Forms in the same page.August 24, 2009 at 4:16 AM
i eventually figured it out. :-)
December 26, 2008 at 11:16 PM
Nifty! Thanks for the great example!
December 27, 2008 at 7:18 PM
Hi,
I've been trying to make this work for the last two days now and it shows the thank you message but I dont get anything in my email. I tried different email accounts, both yahoo and hotmail. I didnt change any code in either of the pages. Can you look at it and tell me whats wrong if you have time? The link is http://www.ranbirkapoor.net/catb/contact.html
Thanks!
December 28, 2008 at 3:02 AM
This has nothing to do with the script, which is working fine. It's probably a problem with the software that is installed on your server and sends the mails. Did you use mail() before in other scripts? Did it work? Also, make sure that you didn't change the original script and you typed the correct e-mail address in the config.php file.
December 29, 2008 at 10:24 PM
This is amazing, just what I needed!! Great job! I had a question… What if I have two forms on my site? One for comments and one for ordering. How can I modify the script so it will work with two different forms with different fields?
Thanks so much!
December 30, 2008 at 4:41 AM
Madiha, good question! I have updated the ZIP file. If you download it, you will find a page sample with 2 forms in the same html page (multiple_forms.html). I will also update this tutorial with an explanation of how you can use more then 1 form in a page.
December 30, 2008 at 9:28 AM
Hi sorry but the zip file does not work, it says there are 0 files in the folder…can you please check for me, I am pretty sure its empty…
Thank you so much for ur help!
December 30, 2008 at 9:39 AM
I've just downloaded the ZIP file (21,1 KB) and extracted it successfully. What software are you using to extract the ZIP archive?
December 30, 2008 at 9:40 AM
Hi, I am using Z-Zip and I also installed Winzip and winzip error is saying "File corrupt, possible transfer error…"
hmmmm…
December 30, 2008 at 9:52 AM
I will send you the ZIP via e-mail and find a solution for this transfer error problem.
December 30, 2008 at 11:37 AM
Thanks alot! It worked great!! This is the best form out there!
I had a quick question about an answer that you posted for somebody here…
The Question was, How do we add Company name, First name, Last name to the email we recieve inside the body of the email?
And you said:
You need to modify $message. Example:
$message = "- Company". $company."\n- First name: ".$first_name."\n- Last name: ".$last_name."\n\n".$message;
But in my contact.php file, I have this info already placed there:
"$message = htmlspecialchars($_POST['message']);"
How do I add that new line in?
Thank you for all your help!
December 30, 2008 at 11:48 AM
Yes, before the line with the mail function add:
$message = "- Company". $company."\n- First name: ".$first_name."\n- Last name: ".$last_name."\n\n".$message;
This way, you will have company, first & last name before the actual message. Notice how I used string concatenation in this situation.
December 30, 2008 at 2:47 PM
Hi, thank you that worked!
But now, it wont validate if a message was input and if it was less than 15 char..
It wont give me an error if i enter NO message…
=/
December 30, 2008 at 2:51 PM
Did you remove $message = htmlspecialchars($_POST['message']); ? I said that you should add that new line before the call to mail() function. I don't know how you modified contact.php. The validation should work 100%!
December 30, 2008 at 2:59 PM
This is what I have:
$message = "- Name: ".$name."\n- Phone: ".$phone."\n\n".$message; htmlspecialchars($_POST['message']);