AJAX Form with CAPTCHA, Realtime Validation and PHP Backend

Create Unlimited Secure Forms with AJAX Form Pro * now available as a WordPress Plugin

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


// 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


Credits: Bit Repository
CSS Library: http://www.bitrepository.com/

html, body  { padding: 0; border: 0px none; }

border: 1px solid #A25965;
height: auto;
width: 90%;
padding: 4px;
background: #F8F0F1;
text-align: left;
-moz-border-radius: 5px;

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;

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:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  <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           


// 'this' refers to the current submitted form
var str = $(this).serialize();

   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>';
result = msg;





return false;




<link rel="stylesheet" type="text/css" href="style.css" />




<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>&nbsp;</label><INPUT class="button" type="submit" name="submit" value="Send Message">






Ajax Contact Form - Show Errors

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.

Capture from the Firebug Console

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.

    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>';
 result = msg;


Ajax Contact Form - Message Sent

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.


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


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;

include 'functions.php';

$name = stripslashes($_POST['name']);
$email = $_POST['email'];
$subject = stripslashes($_POST['subject']);
$message = stripslashes($_POST['message']);

$error = '';

// Check name

$error .= 'Please enter your name.';

// Check 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.";

$mail = mail(WEBMASTER_EMAIL, $subject, $message,
     "From: ".$name." <".$email.">rn"
    ."Reply-To: ".$email."rn"
    ."X-Mailer: PHP/" . phpversion());

echo 'OK';

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

This version contains the basic features that were discussed in the tutorial.

Download | View Demo

Get Premium

This is a premium 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 Pro

Create unlimited AJAX Forms in the same page/multiple pages
You can generate as many forms as you like and easily include them anywhere you wish. Each form has its own configuration file. For instance, you can enable the CAPTCHA for a form, while you can disable it for another form.
RealTime Validator
This makes the form completion process interactive. The errors show/hide while the user fills the form. If this feature is disabled, then all the errors will show above the form once the user clicks the submit button.
Powerful CAPTCHA: Anti-Spam Verification Image
You can use letters, numbers or both (can be enabled/disabled). The verification image can be refreshed in case the user is having trouble in recognizing the characters. While the user types the security code the script verifies it in the background. Once the user types the right characters, it automatically shows (in real-time) a successful message to the user. Unlike many AJAX CAPTCHAs out there that rely on JavaScript as an Anti-spam measure and have a medium security level, the one I have chosen to implement uses PHP to securely generate and register the required code in the background. The comparison is a case-insensitive one in order to make the filling process easier without annoying the person who fills the security code.
Auto Responder
Useful to notify your visitors that their message was successfully sent (e.g. "Your message has been successfully sent. We will reply to your inquiry within 48 hours"). For instance, it can be used while you're in vacation and let the users know that you will reply to them as soon as possible. The headers (from name, email) can be set in the configuration file.
Send Mail with Attachments
This application supports adding file attachments to the data that is sent through the AJAX Forms. You can either receive the links to the uploaded files or the actual attachments to the mail message. I'd prefer the former method, because often the mails with many attachments are automatically reported as SPAM. This "file attachment" feature is also available if you use the AJAX Form inside a Lightbox.
Fully (CSS & HTML) Customizable: Supports any form element
Easily add/remove fields, change notifications, customize the mail settings. The following fields are supported: input text boxes, textareas, single/multiple selects, checkboxes, radios. This way, you can create more complex web forms and surveys without editing any HTML code.
Turns into a simple PHP Contact Form if JavaScript is disabled
Is the visitor in that 3% of people that have JS disabled? No worries! The form degrades gracefully into a basic non-AJAX PHP Contact Form.
Clean Layout (uses LABELs, DIVs and Paragraphs)
Lightbox integration (Powered by Fancybox)
Display the form in a Mac-style "lightbox" that floats overtop of web page.
Modal Form with Sliding Transition (Left & Top)
Add some style to your pages by loading the forms in a fancy way
Redirect to Thank You page after Successful Submission
If you do not want to show the basic successful confirmation message, you can redirect the user to a customized thank you page
Send mails using either mail() function or through SMTP
Besides the basic mail() function, you can use the SMTP method to send the mail. This way, chances are higher the message won't end in the JUNK/SPAM folder, especially if lot of mails are sent.
Easily send mail to multiple recipients/webmasters
You have the option to set as many recipients you want to get the mail that is sent through the forms. Each form has its recipients. For instance, one can be set to send the form information to the Marketing Department while other can be set to send the information to the Billing Department.
HTML Code Separated from the PHP Code
The script is powered by the Smarty template which is meant to ease the process of web design by separating the (logic) PHP Code from the (output) HTML code. Beside the fact that things are kept clean, it is also easier for you to make changes to the HTML structure without touching the PHP code.
100% Source Code Available
You have the possibility to customize the script as you wish. NO encrypted or obfuscated code!
A help page that guides you through the setup process (1. Basic Settings, 2. HTML Structure, 3. CSS Files and Structure, 4. JavaScript, 5. Sources and Credits)

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
  • 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 90 days money back guarantee.
  • If for any reason you are not satisfied with this script you can request a refund within 3 months from the purchase date and I will buy the script back from you. No questions asked!

Add to Cart

  • Licenses are lifetime
  • Customer Support is offered within 24 hours
  • Payments are processed through PayPal or 2Checkout
  • Digital delivery is provided by WP eStore

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”Jared (http://www.haroldsmithbicycle.com/)

“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.”Kevin Morrison (NW Interactive designs)

“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.”Rolando Martinez Barron (http://www.matamoros.com/)

“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.”Kayhan Yalinkilic

Comment via Facebook


553 Replies to "AJAX Form with CAPTCHA, Realtime Validation and PHP Backend"

  1. Hello Gabriel
    I bought the tool and it works like I wanted it. But now I need the function to enter data into a mysql database. Can you help me here?
    Did you give me a sample code. As I read this to be entered into the parse.php.

  2. … and I’ve got another question: how can I put two text fields next to each other? Example: ZIP and city or first name and last name. is this possible. Excuse my bad english, I hope you understand what I mean. German would be better to describe correctly all.

  3. We bought a licensed version for this. We are trying to use this on a site and it keeps showing the Submitting icon after clicking submit. The email is triggered and all data validated. How do we redirect this to some page or how do we ensure the Submitting actually completes its action? I am not much of a programmer.

  4. Hi
    I have bought your script. I will need to display fields (say: input,select, ect.) in two colomn – one beside other.
    Is it possibile?


  5. Hi Gabriel
    I just purchased the single license. I would like to know if it is possible to upgrade to the extended license?
    Kind regards

    1. Yes, it’s possible. I will send you the purchase link with a coupon code (as a current customer).

      1. Hi Gabriel,
        Thanks for your response. When will you be able to email me the purchase link?

        1. I’ve just sent you the purchase links.

  6. This is a great application. But Gabriel you prommised me a database “updated version” last year already. Up to date I am getting no response from you and can also not download the aplication any more.
    Please help

    1. Llewellyn, thanks for getting back to me. It took me a while to release the new version of AJAX Form Pro and believe me, you will understand the reason you had to wait when you will use the new script. My apologies for the inconveniences this delay might have caused to you. I’ll send you the new tool right away ;-)

      1. Gabriel, thanks this version is WOW. I think you have a winner here :) great work.

        1. Thank you, Llewellyn! I’m really happy to see that my hard work pays off <:-P

  7. Why such an increase in the price? The single license was $17US less than a month ago. Same thing with the extended license, increasing from $67 to $127.
    Personally I think it’s a bit too much.

    1. Thank you for your comment. I’m not sure you’ve noticed, but AJAX Form Pro v2 with Control Panel was launched that is a far better web app than the previous version. It basically allows you to easily create as many forms as you want and integrate them into your website in a couple of minutes. I’ve spent months developing and testing the new application (fixing bugs, adding new features, improving code quality) which is even today in a continuously improvement. I personally believe the $27 price is not much at all considering that you get a lifetime license for a fixed price, which you can use to create as many forms as you wish (unlimited submissions) on a single website. If you take a look at some “Online Form Builders” out there, you will see that they charge you a monthly fee and you keep the form on their servers. It’s like using WordPress.com to host your blog instead of having your own server with the WordPress platform customized as you wish. The “Extended” license lets you setup as many forms as you wish in unlimited projects for your clients. If you are a Web Developer that needs to constantly create forms for his customers, then I believe $127 is an convenient price. You can even include the script in commercial scripts. The only thing you can not do is to resell it and claim the script as yours.

      PS: The new version was just launched and I’m offering discounts for it (check the latest post on the website). If you are an existing customer, I can offer you a special discount for any licenses you might need.

  8. I just learned about this today but $127 is really steep for a form processor. Any chance of a sale coming soon?

    Also, does this use the popular Bassistance.de validation plugin? That’s the one I’d like to see integrated the most. I have several form scripts that use it and it’s the best so far. In your demo you seem to check for numeric, text etc but nothing to validate credit cards etc.

    1. I might decrease the price for the “Extended” license in the near future. The other prices will remain the same. I’ve explained my reasons in my above reply.

      No, the script does not use Bassistance.de validation plugin. It has its own validator. Credit Card validation is not implemented, but I am thinking seriously in adding it. One step at a time ;)

  9. Thanks very much for this, worked really well for what I required and was nice and straightforward to implement too.


  10. Parse error: syntax error, unexpected ‘@’ in /home/a2593233/public_html/contact.php on line 52

    i am getting this error message,
    can you help me please

  11. Is it possible to use the file upload form on a smartphone?! I tested your example “Advanced Contact Form” to Add Attachement, but this didn’t worked. I select an image, clicked Upload Files(s) and then it stopped.
    Which php version do I need 5.2+

  12. Hi,

    I have used the simple contact form on my site. Everything validates and I have followed all your instructions but when I send test messages, they never come through and it confirms that the message has been sent…I have no idea what could be happening…Any chance you can help out?

Leave a Reply

* = required fields
Like our script? Rate it at PHP Hot Scripts

  (will not be published)

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Note: If you want to post CODE Snippets, please make them postable first!
(e.g. <br /> should be converted to &lt;br /&gt;)


  • The comment must be relevant with the topic of the post.
  • Only comments with real email addresses will get approved. So, emails like 'abc@domain.com' will not be accepted.
  • Do not post the same message in multiple articles through the site.
  • Do not post advertisements, junk mail or pyramid schemes.
  • In case you post a link to another site, please explain briefly where the link goes as a courtesy to other users.
  • Do not post comments such as: "Thank you", "Awesome", "Nice tutorial", "Merci", etc.