AJAX Form with CAPTCHA, Realtime Validation and PHP Backend

The aim of this basic tutorial is to help you to create a simple (table-less) AJAX Contact Form using jQuery & PHP. It will give you an idea of how you can create similar web applications using jQuery and AJAX. 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.

Step 1 – Creating the configuration file


// To
define("WEBMASTER_EMAIL", "your_name@your-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; }

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


	<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           
	 jQuery(document).ready(function($) {

		$("#ajax-contact-form").submit(function() {
			// 'this' refers to the current submitted form
			var str = $(this).serialize();
			   type: "POST",
			   url: "contact.php",
			   data: str,
		   	   success: function(msg) {	 
					// Message Sent? Show the 'Thank You' message and hide the form 
					if(msg == 'OK')
						result = '<div class="notification_ok">Your message has been sent. Thank you!</div>';
					} else {
						result = msg;

			return false;
	<link rel="stylesheet" type="text/css" href="style.css" />
 	<div align="center">
		<h3>A Tableless Contact Form (jQuery &amp; AJAX)</h3>
		<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="">
			<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 jQuery(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) {	 
					// Message Sent? Show the 'Thank You' message and hide the form 
					if(msg == 'OK')
						result = '<div class="notification_ok">Your message has been sent. Thank you!</div>';
					} else {
						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;
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

This version contains the basic features that were discussed in the tutorial.
Download | View Demo

Get Advanced

This is an advanced AJAX Contact Form builder that can be used to built a custom contact form. It’s a free and very light version of AJAX Form Pro, my premium form builder. This version is available for BitRepository.com subscribers. Type your details below, confirm your email and you will receive the download link in your inbox.


Get Premium

AJAX Form Pro is a premium Multi-usage AJAX Form builder with lots of features and support for all form elements. Starts from $13.95.

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



  1. says


    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?

  2. Marnix says

    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+

  3. maruf says

    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

  4. CC says

    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.

    • Gabriel C.Gabriel C. says

      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 😉

  5. Joe says

    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.

    • Gabriel C.Gabriel C. says

      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.

  6. says

    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

    • Gabriel C.Gabriel C. says

      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 😉

  7. Joseph says

    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

  8. franco says

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


  9. Vishal says

    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.

  10. Marcel says

    … 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.

  11. Marcel Fellmann says

    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.

  12. says

    Thank you for sharing us this integration. I suppose the feature to redirect the user to a thank-you.php page after submit was not a feasible option for you, since you could have added the Google Analytics code on that page. However, most of those who are using AJAX Form Pro are not using the feature and prefer to keep their visitors on the same page. So, I hope your comment would be helpful for those who are looking to setup a funnel.

  13. Mike says

    Hi Gabriel

    Impressive script, and the form exactly what I have been looking for. But does appear to be for developers and people who know how to write code.

    Fopr someone like myself, who has limited experience with websites and code, the comments posted are scary, if they have problems with the code then a layman definitely will.

    Your extended version explains you will configure and upload 2 forms to 2 websites, but does not explain how this script comes, is it a complete form then it gets modified? Not enough information for people like myself who like your script and forms to purchase and not know if there is proper help afterwards

    Kind Regards


  14. Salvage C says

    Hello, I have two questions before I buy this. 1) I downloaded the free form and I realised that the email that it sends, doesn not have subject nor sender nor header.Why is this? Is the premium one different? 2)About Developer License: Does it mean I cant use the form in a site I design for clients? It says unlimited and unlimited hosts so I should be able to use it on clients sites, no?

  15. Matt Meaney says


    I purchased the extender version back in June this year. I can’t seem to find any documentation or example of using the attachment upload feature. Please can you help me? Also, are there updated versions of the scripts available, as I think I read you did some sort of update in July?


  16. Ray says

    I had some problems getting this to work on IE, but recently got it working. I like the functionality and cleanliness of your basic form and have modified the CSS to my own needs.

    Then I decided to upgrade a contact form with this one. This form would be nested in mb_container, only that plugin uses newer Jquery and I can’t get them to play nice. Your demo files used jquery.1.2.6-min, I tried a version four and a fiver, which work for the container, but they don’t animate the notifications of your form. My setup looks too PRO to go back, so what are my options? Can you think of something I would need to update to get this to work with newer jquery libraries?

    Great work otherwise. Kudos.

  17. Thomas says

    Hi Gabriel,

    Great script! Purchased the Pro version and am very happy. Couple of questions:

    1. Can I set a hidden field in the form?

    2. Is it possible to do inline Ajax validation, i.e. is user name already in a database etc?

    Many thanks, Thomas

  18. Chris says


    Can this be used on Microsoft-IIS/7.5 Server?

    Clearly a lot of these forms integrate with Linux php mail and the Sendmail program.

    But Ive been asked to host on Microsoft-IIS/7.5 Server. I believe it has php installed but uses SMTP only.
    Ive no experience of Microsoft-IIS/7.5 Server.

    Honest feedback required because im happy to pay a fix if it can work under Microsoft-IIS/7.5 Server

  19. guntram says

    sorry for the frequency of my posts right now :(

    but i wrote
    “i was experiencing an issue with checkboxes on your premium version of the afp.”

    of course i was experiencing an issue with dropdown-select boxes and not with checkboxes!!

  20. guntram says


    if the datepicker is empty and you set the option to validate it, the form shows the error and does not submit.

    but i did not want this to be an option so i just setted the datepicker to a start date so that there will always be a date picked and the user can only change it.

    if you concentrate on that a little, you can also check if the user deletes the field and set a date again into the field.

    don’t know if you can verify a certain date frame, but i think you can set the datepicker itself to some range of valid dates…

  21. guntram says

    hi dude!

    i was experiencing an issue with checkboxes on your premium version of the afp.

    i was stuck with false option values getting setted if i use dropdowns.

    so the html was something like:

    Technical Question

    the solution was, after a lot of checking out ;), that i have to set the layout to 1 instead of 3…

    this brought me to the desired output of:

    Technical Question

    i am using this on a facebook app!
    on a usual webpage this issue does not appear somehow!


  22. emre a says

    Well, I just purchased the developer version today and applied to one of my client’s web page and I can tell this will save me some quality time on my other projects as well :). Thank you for putting this together. It is def. worth for the money.

  23. Julie says

    I am searching for a form tool that creates & processes. This one looks very promising! The form needs to support end user submissions that will be stored to a database and emailed to an admin. Only three fields are needed: Email, Subject & Comment.

    Is this tool able to do this out of the box? If not is customization as a purchased service available?


    • Gabriel C.Gabriel C. says

      @Julie, the script can create the form you want. However, it doesn’t have the feature of adding the data into a MySQL database. If you purchase the extended version of the script, I will add that customization for you (add form data into database and page to see the data that was previously inserted).


Leave a Reply

Your email address will not be published. Required fields are marked *