AJAX Form with CAPTCHA, Realtime Validation and PHP Backend

Create Unlimited Secure Forms with AJAX Form Pro

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

</div>

</fieldset>

</div>

 </center>

 </body>
</html>

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.

    $.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);
 });
 }  

  });

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.

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.

Download | View Demo

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

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.
Tableless
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!
Documentation
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

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!
To get instant access to this script right now — simply select your license type below and click your desired payment method.
Pick a license that suits you:
$
27
Suitable for installing on a single website or intranet site project. A single license is for one domain.
Lets you install unlimited copies of the script. Unlimited license is for unlimited personal hosts (domains or sub-domains).
Includes both the developer and the commercial license. You CAN use this script in your clients' projects. However, you DO NOT have the right to re-sell it. Example: you are allowed to incorporate the script in a Wordpress Theme that is sold on Themeforest.net or into a CMS you made for a client of yours.
Pay with PayPal orPay with Credit Card
After checkout, you'll get immediate access to the script. Place your order right now to get started and get all features of AJAX Form Builder.
  • 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" - 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

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

  1. Hi Gabriel,

    I was playing with your demo and when I disabled javascript in the browser the validation doesn’t work.

    I am planning to buy the premium version. Will I have php validation in place in that version?(in case the Js is disabled)

    1. The real time validation can’t work without JavaScript enabled. However, the fields are validated in PHP to prevent SPAM and the script sends the mail only if the required fields are filled correctly. I will add a feature that will gracefully degrade the application for users with JS disabled and notify you when the script will be updated ;)

  2. I loaded the form inside a facebox, it works fine with IE and Firefox, but not in Safari I keep getting a pop-up window with a “success!” displayed. when I click on submit…

    Any ideas on how to fix it?

  3. its look cool and sound. but what about the SEO feature.url are not changed

  4. Hi there! This is a really nice form, I’m interested in purchasing the premium version. I’ve tested it and it works, everything nice n neat! One small problem though:

    I need it for a Greek website. When I send a Greek message and receive it in my inbox, Thunderbird does not “realize” that this is in UTF-8, so, the message appears with “jibberish” at start. When I set the encoding afterwards, it’s readable. How can I “tell” the recipient that “hey, this is a UTF-8 message”. Can I set it somehow, and where?

    Thanks a lot, good work and looking forward to hearing from you :)

    Dimitris

    1. Hello Dimitris,

      You need to edit the code where the mail() function is used. The UTF-8 charset must be added to the mail headers. Here’s a URL that can help you with this endeavor:

      http://www.php.net/manual/en/function.mail.php#92976

      PS: You can use mail() to send HTML mails too. You just need to add the right headers ;-)

      Gabe

  5. i get this error: {“sender_name”:1,”sender_email_none”:1,”sender_subject”:1,”sender_message”:1,”security_code”:1,”status”:1} what could be causing it!?

    1. This is not an error. It is the output resulted from parse.php. The form validation triggers after DOM is ready (all page elements are loaded). You probably clicked “Submit” before the page loaded completely. I will think of a solution for this too.

      1. I take this error too. I use jquery 1.4.2 when I return to 1.3.2 thats working again.

      2. i ALSO get this error: {“sender_name”:1,”sender_email_none”:1,”sender_subject”:1,”sender_message”:1,”security_code”:1,”status”:1} what could be causing it!?

        i found it needs 2 fields entered before it wont error.

  6. Hi Gabe,
    Great script, just a quick note. phpmailer isnt liking PHP 5.3.

    Is giving me an error on line 470 split().
    Have tried using preg_split() but no luck.

    I think ts fine with previous versions of PHP.

    Let me know if you find a solution.

    Cheers

  7. Great script. Still trying to learn all that it does.

    Is there a way to make the confirmation email (auto_responder) not show the reply-to email address that the form is set to send to?

    like I want to set the reply-to email in the confirmation email to something like no-reply@domain.com rather than the email the form is sending the message to.

    Any thoughts? Thank you for your time.

    Regards,
    Stan

  8. Hi Thanks for the script.

    When the form is submited. I get
    Your message has been sent. Thank you!

    But when I go to my in box there’s no email address, name or subject only what’s be put into the comments box.

    Please can you advise
    Many Thanks
    Clifford

    1. hey man i got your same problem …have you resolved the problem
      Regards

  9. This worked perfectly for me! Uploaded, changed a few settings, and all worked.

    Thanks!

  10. Hello Gabriel-
    I love this script!!! Everything is working perfect but one thing I can’t figure out is that I do not receive the actual emails people send, while users do receive their confirmation emails without problems.

    Could you give me some assistance to where the fix for this is?

    Thanks in advance!

  11. Hi,

    thank you so much for this script.

    I have spent countless hours trying to implement a contact form into my Drupal site as the inbuilt one was not up to scratch.

    This form works an absolute treat and does not interfere with any of the existing block styles.

    I just have to tweak the styling a little now to fit more comfortable into my page.

    Kind regards..,

    MT. ;0)

  12. Hi,

    after installing the form yesterday and it worked perfectly for some reason today it is producing an error dialog everytime a keypress is made in the security code textbox:-

    Error occured:[object XMLHttp Request]

    I ahve not changed anything in the form from yesterday when it was working, is this an error with my server or something?

    Regards..,

    MT

    1. What’s the URL to the Contact Form? Have you made any changes to the script since yesterday?

      1. Hi,

        the form is at:-

        http://www.madtogger.co.uk/page/contact

        the only thing that I have done this morning was to upload an ajax-loader.gif into the images folder as I saw there was not one there and it was being called via js.

        I can’t really see how that would cause this.

        I have got my host looking into the error to see if it could be server related but I would appreciate your point of view.

        Regards..,

        MT

        1. Hi,

          very strangely I have just checked the form again after my last post and it seems to be working without errors, how wierd, must have been server related, sorry for the inconvenience.

          I also see that you have sent through a test message via the form, so that worked then.

          Regards..,

          MT

          1. Yes, just sent a test message and everything worked like a charm ;-)

          2. I also get the “Error occurred: [object XMLHttp Request]” in a pop-up dialog for a period of 5-10 minute every now and then. No changes were done before, during or after. It’s pretty annoying since the pop up message goes into a loop and you can’t even close the browser. I have to go into task manager and end the process manually. I do not wish that upon any of my visitors trying to contact me :/

            Any ideas?

          3. @Adam, can you share us the URL to the Contact Form? That would be helpful to figure out what’s really the problem.

          4. I forgot to mention it only happens when typing out the 2nd or 3rd letter of the captcha code. It happens rarely but I had it happen to me yesterday.

            http://www.akrilic.com/contact.php

            http://www.akrilic.com/contactphp/contact-script.php

            I did one minor change in the contact-script.php, and that’s move the captcha div to display next to the input-field ( I was having layout issues). But that isn’t the cause of the error since I had the it happen to me a few times beforehand.

          5. OH, it just happened to me a few seconds ago, if you’re following this live check it out

          6. @Adam, I made several tests and I didn’t see the error. What browser are you using? When you will see this error next time, please make a screenshot and share the image with us. Upload it somewhere on your site.

          7. http://www.akrilic.com/img/xmlhttp.png

            Just as I was checking to see if the image loaded onto the server, I realized something.

            I was at akrilic.com, not http://WWW.akrilic.com
            Then I remembered that on my contact page, I’m <?php including contact-script.php through my full address (including www.) , because including it on the page without the full address didn't work.

            I think I'll just copy the contents of contact-script.php into the body of my contact page (and moving the contact-app directory up a few), instead of <?php including it. It should work, I'll try it out later. Unless you know of simpler solution?

            Anyway, thank you for an awesome script!
            -NOW- i love it :D

          8. @Adam, the security code is verified using AJAX. When you try to load data from a different host you get an error (‘Permission denied’ – when using IE – shows when click on the “Error on page” from the status bar).

            Here’s a URL address that explains you this more properly:
            http://www.captain.at/howto-ajax-permission-denied-xmlhttprequest.php

            >>> If the page with the XMLHttpRequest is on a http:// URI (on a webserver), it is not possible to fetch data from another domain!!! This is a security measure of Mozilla/Firefox.

          9. Initial Problem:
            <?php include '/contact-script.php'; ?

            Minor Solution:
            <?php include 'http://www.akrilic.com/contact-script.php'; ?
            (full URL) – the problem with this is that I would get the XmlHttp error when visiting the page without the www. prefix.

            Full solution:
            <?php include 'contact-script.php'; ?
            (without full URL and without a ‘/’ slash in front.

            Very simple, I guess I jumped the gun on that one

            Like they say: It’s always a simple directory issue.

          10. @Adam – Well, this is not a solution. That include function has nothing to do with the path that is generated in the JavaScript code. I will consider upgrading this script so it would work flawlessly with/without www extension.

  13. Hi,

    sorry to bother you again but the error I spoke about earlier has come back again and this shows when using Google Chrome.

    I have tested the form in IE8 and where I did not get the error dialog when typing in the security box, when I hit send I received this error message on a blank webpage:-

    {“security_code”:2,”status”:1}

    obviously the webpage was blank apart from this and was page:-

    http://www.madtogger.co.uk/contact-app/parse.php

    I would really appreciate any pointers here, could this be a server thing or not?

    Regards..,

    MT

  14. Hi,

    did a little research about the [object XMLHttp Request] error and found that if I set;

    var js_realtime_validator to false in (init.js) this error does not appear when typing in the image captcha security box but the form will not send either.

    I don’t really know enough to figure out why this is happening or why setting the variable to false causes the error dialog box not to appear.

    Is there anything I can do to resolve this?

    Regards..,

    MT

  15. hello, can you please help me to add turkish language support to this beautiful script ?
    I changed it to utf-8. also tried windows-1254 charset but it didnt work.
    Messages are fine but subject names show “????” characters.

    Any help will be appreciated.

  16. It would be great to prevent users from submitting the form multiple times.

    Adding something like this to line 47 (contact-script.php):
    onClick="this.disabled=true; this.value='Sending'; this.form.submit();"

    Unfortunately, with the above code, if a user gets an error from name, email, subject, etc, then they won't get a second chance since the button is disabled.

    Is there a way to activate this only after they've passed through all the checkpoints?

    1. Yes, that’s a good idea. I will consider upgrading the script, but I will not use inline JavaScript. I am trying to keep the HTML code as clean as possible. When the user clicks submit, the button is disabled and a loading spinner .GIF image can show until either the error or confirmation message appears.

  17. hi.. i’m having one problem. it’s conflict with other jquery. i have lavalamp menu in my page when i use this script then lavamenu not work… i tested many way but i can’t fix it… can you check this please…

    http://207.210.75.157/~team/frm/contact_us3.php
    http://207.210.75.157/~team/frm/contact_us2.php

    mainly init.js file conflict with other.

    thanks

  18. Hi there – nice script thank you. It all seems to work but when I get the message all i see in the email is the actual message and not the name or email. Any idea what may be going wrong?

  19. Thanks for the script, I am planning on using on a site in the very near future. If I wanted to add new fields to appear in the email, how would I go about that?

    I have tried and have the alert function working, but am not sure where to add the extra item for it to appear on the email.

    I assume it goes somewhere in here


    $mail = mail(WEBMASTER_EMAIL, $subject, $address,
    "From: ".$name." \r\n"
    ."Reply-To: ".$email."\r\n"
    ."X-Mailer: PHP/" . phpversion());

    my new element is called $postcode, but I am planning on adding quite a few.

    Any help would be greatly received.

    Regards
    Jan

    1. @Jan Leeks, consider checking the comment #615. Here’s the URL:

      http://www.bitrepository.com/a-simple-ajax-contact-form-with-php-validation.html/comment-page-1#comment-615

      It’s a reply to someone who wanted to know how to add a new field called “Company”. Note how I’ve explained a way to add the value of “company” field inside the subject. You can do the same for the message.

      PS: If you’re looking for an easier way to add fields and a better contact form you can purchase the premium version of this script for just $3 (using the right discount code) ;-)

      Good luck!

      1. Thanks – I purchased the premium version earlier today actually, so looking forward to getting my teeth into that later on.

        thanks

        jan

  20. This really great, thank you so much, i love this stuff

  21. I purchased a theme that includes this contact form, and i am having on problem. I need for the messages that are submitted to me, to appear they are coming from my email address. It has to be this way to get through the spam filters. Is there someplace i can change it, as it currently shows the senders address?

  22. I purchased the ajacx contact form script several days ago, and although the emails aer sent, i am having a problem with the capthca. Event hough i enter the correct code I keep get the message incorrect code.
    It apears that both sessions and cookies are not working as expected (ie im passing session id in url). I think that cookies/sessions are being set but cannot be read because we are not trendedgecapitals.com. Do you have a workaround for this?
    Thanks

  23. Hi, I’m new in web designing, just trying to get your code into my website.

    I’m trying to put your code into my reservation page here http://www.kamarhotel.biz/ajax/reservation2.html but it seems something is wrong as the date is not loading but I don’t know where I did wrong. Can you advise me?

    I will put credit to you at the bottom of the page, if allowed. Appreciate if you can enlighten me :)

    Regards,
    Rico

    1. Hello,

      The information that is filled on the form is sent to contact.php. However, when I access http://www.kamarhotel.biz/ajax/contact.php, I get a “Page not found” error. So consider downloading the tutorial files and get contact.php. Make sure to modified it to your needs. If you want an easier way to add/edit/remove fields you can purchase the Premium AJAX Contact Form for just $5 USD.

      Cheers!

  24. Clueless why your basic form is not returning form fields.

    I submit and in my email I see no name, email address, or subject, only comments.

    Thanks

    1. Also how do you make it send email messsage to visitors?

      Thanks

    2. It is not clueless. You just have to edit the contact.php page and add the fields values inside the mail body message. Also, both the name and the subject are shown because they were added in the mail headers (from: [field name value], subject: [field subject value]).

  25. Is it possible you can you check the contact.php script below as it seem to only have only the (if) statements so I am not clear on what you mean sorry. I thought that as long as the fields were in contact.html they will return their values in my email once sent.

    I also provide a test
    http://www.destiny-explorer.com/formtest123/contact.html

    ===============

    <?php
    /*
    Hello World
    */

    include 'config.php';

    error_reporting (E_ALL ^ E_NOTICE);

    $post = (!empty($_POST)) ? true : false;

    if($post)
    {
    include 'functions.php';

    $name = stripslashes($_POST['name']);
    $email = trim($_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) < 5)
    {
    $error .= "Please enter your message. It should have at least 5 characters.”;
    }

    if(!$error)
    {
    $mail = mail(WEBMASTER_EMAIL, $subject, $message,
    “From: “.$name.” \r\n”
    .”Reply-To: “.$email.”\r\n”
    .”X-Mailer: PHP/” . phpversion());

    if($mail)
    {
    echo ‘OK’;
    }

    }
    else
    {
    echo ”.$error.”;
    }

    }

    ?>

    1. In order to include the other fields inside the mail body, you have to edit the $message variable. I’ve explained this to someone some time ago. You can check the following comment reply: http://bit.ly/cybzSr

      PS: You can purchase the premium AJAX Contact Form for just $5. It has lots of feature and it’s much better than the basic version.

      1. Thanks Gabriel this helps.

        Dave

  26. Thanks, works like a charm ! Some little adjustments to fit my needs (damn! I hate Internet Explorer,it can’t display a page normally ! Should be eradicated).
    The script is on

    PS. Gabriel, you are Romanian ?

    1. I am glad that you managed to successfully install the premium script. Most of the complains I got are regarding the initial setup of the AJAX Contact Form. I agree, Internet Explorer has issues. However, I did make the script to work with IE too. And yes, I am a Romanian [web developer].

  27. Indeed, the form works with IE, the bugs are in the integration part (in a <table> or in a <div> ),that’s where (thanks God) CSS play a major role. Thanks again.

    PS: Felicit?ri, continu? tot a?a !

  28. Hi Gabriel,

    I’m interested in getting a single licence, but wondered if I could upgrade to the unlimited license later if I paid the difference?

    1. Hello Dave,

      Yes, you can make the upgrade to the Unlimited License by paying the difference. Just let me know when you are planning to make the upgrade, if you will first get the Single License.

      Cheers,
      Gabe

  29. How can I add a radio group and checkboxes?

    1. Chase, this feature is not yet added. I am working on it because there were people who requested it. However, can you tell me how do you want to add the checkboxes and radios? Do you want to make them mandatory? Let me know and I will see what I can do.

      PS: You can add checkboxes and radio groups but you have to edit the core scripts and you need to be familiar with PHP and JavaScript.

  30. I took out (sender_subject) and tyhe script isn’t inputting the default (AR_SUBJECT).

    Not much modification to beautiful script.

    1. Chase, AR_SUBJECT is actually the Auto-Responder Subject. It has nothing to do with the subject of the mail that the admin receives.

      1. Why won’t it display a email subject. I removed (sender_subject) , but I see on line: 119 there is a default subject.

        1. If you remove the ‘sender_subject’ field, the default subject will be used. You mentioned that you see the default subject on line 119. In which file? I’m a little confused because I do not know if you modified the script files.

          1. I’ve modified the fields, but that’s it. The default subject isn’t showing up in our emails.

        2. I am sorry, but you must have done something wrong. Did you downloaded the latest version of the AJAX Contact Form?

          1. I’m trying to add event tracking for Google analytics. I want to track form onSubmit. Can you tell me best way to implement this into your script.
            Gabriel, see if you can help me.

  31. Hello

    Does the unlimited license explicitly allow this functionality to be resold as part of a WordPress theme (on ThemeForest in my case)?

    thanks
    Anthony

    1. The developer license allows the user to use the script on all his personal websites. To also have the right to include the script in another commercial product (for instance on ThemeForest or CodeCanyon) you should purchase the “Extended” License. I’ve updated the post and you should see it in the drop-down.

  32. I just bought the contactform, it looks great, but it doesn’t send my message. This is the link: http://www.djxtremer.nl/cnt/contact-script.php

    1. I just checked the URL and the following error came to my attention:

      Invalid address: WEBMASTER_EMAIL > You must provide at least one recipient email address.

      You are not the first one that tells me about it. This is because you haven’t setup correctly your email address in common.php. It should be something like:

      define('WEBMASTER_EMAIL', 'yourname@domain.com');

      1. Thanks man! It’s working fine now. I’m a PHP, code noob haha..

  33. Hi there

    Great script, however, I’ve now bought a developer script and uploaded the script and I tried it once, it kinda worked, but it kept on saying Submitting and when I changed something on the common.php file, it now does not want to submit at all, I’m working through a proxy server though which caches for some time…

    So I cant really tell if I did something right or wrong, can I submit the file to you so you can check.

    1. The reason you keep seeing “Submitting…” is due to the fact that parse.php does not only output the JSON values but also some errors that are generated in parse.php including but not limited to: not settings the right path to include the necessary files, 3rd party scripts that are used in conjunction with this script. It all comes down to integrating the script properly into the website.

      I am willing to integrate the form for you free of charge. I just need the FTP information for your website. Please contact me privately for discussing further about this.

  34. Thank you for the quick response. I’ve managed to figure the issue.

    It was a problem of copying the email array for a new field and I forgot to remove the ‘email’ => 1

  35. Hello,
    I need to replicate this form for each record in a list that is being displayed on php page. Let’s say there is a list of dealers, and we need to add ability so that our website visitor can click a “send email” link, fill the form and send it.

    I am able to replicate this contact form of yours, but when i try to submit the blank form, i get js alert “Success!”. Though the first form in the list of records works. The rest show the message i mentioned above.

    Any help is appreciated.

    1. The ID of the form needs to be unique, as well as the other IDs from the page. Take a look at the multiple_forms.html file from the downloaded package. You will understand what I mean. That “Success” js alert should not be shown since we are using AJAX to submit the form. It’s just a dummy action (just to be there).

  36. I want to purchase the premium one. But was wondering if it also has the HTML page version. Thank you.

    1. The form is built dynamically, therefore it uses PHP to add the fields that you set them in a configuration file. However, you can copy the source from the generated form and use it in a HTML page. You also have to make sure that the fields configuration remains the same in the PHP configuration file (common.php). If you want to have a new HTML page with different fields, you need to edit common.php and run the script again. It will generate you the new HTML code to copy and paste in your HTML file. It’s quite easy.

      1. you mention here to generate html by running a script how exactly is this done?

  37. from where will i get the jquery-1.2.6.min.js

    1. Get the latest jQuery version from http://jquery.com/

  38. Hi Gabriel.

    Just a quick question about the premium form.

    I want to confirm how this form would function if loaded into an iframe.

    If I used a jquery lightbox to display the form in a floating iframe, would the way the form adjusts it’s length vertically to display error and success messages break the iframe window height?

    I’m guessing that if I just add a height parameter to the iframe request that is static with enough padding that it should not be an issue but curious anyway to understand the implications of not setting a height.

    Thanks

  39. I don’t understand where the grey outer border for the whole form comes from. I’ve tried everything to find the CSS that adds it with no luck.

    How is that border added?

    Thanks

  40. Hey. I need to add a mandatory Check Box at the end of my form. I bought the Premium version, just not seeing a way to do this. Please help!

    1. @Cary, at the moment, you can’t add the checkbox from common.php. Since you are not the first one who is asking for a way to do this, I will consider updating the script and send an update to everyone that purchased it. You need to add the checkbox manually. You can take a look how the “notify me” checkbox is added and try to add this one. If you are familiar with PHP and JavaScript, this should be easy to add. You just have to study the script. If you still can’t figure out how to do it, then let me know and I will try to send you the modified script. I am out of the country now and I do not have an internet connection available all the time. However, I will do my best to assist you. Good luck!

  41. Hi!

    Bought the premium developer version.

    It worked like a charm at first.
    now i am getting this error:

    The mail cannot be sent due to an internal error. Please retry later!

    Server issues?

    1. Yes, it must be a server issue. You said it worked like a charm. Make sure you haven’t changed any server settings. Consider testing the script on other server too. Keep me updated! Good luck!

  42. This is a great form, just what i was looking for. i’m having trouble with the textbox though. if you type a continuous sentence, it works fine. but when i hit return in the textbox to make separate paragraphs, i get an error message that reads:

    “Warning: mail() [function.mail]: SMTP server response: 451 See http://pobox.com/~djb/docs/smtplf.html. in D:\Hosting\2334727\html\contact.php on line 57″

    Can you help me out with this? Thanks!

    1. Have you tried other contact forms and you got the same warning? Usually, the mail() errors are from the server settings. I have never received such a complaint (either continuous sentence or sentence paragraphs) regarding the content of the message that is sent. f you can’t solve this problem on your own, can you send me the ftp details for your website to support ( a-t ) bitrepository ( . ) com? I can check if everything was installed correctly and give you an update regarding the situation.

      1. ok, i was just doing some research, and i found an article that explains this error. I think the problem is in the message variable.

        “It looks like while Unix-based systems recognize \n character (the equivalent in PHP of LF – line feed) as a newline even when sending emails, Windows systems are stricter in comunicating using some textual Internet Protocols (such as SMTP) that mandate the line terminator to be the ASCII CR+LF (carriage return + line feed) sequence, which is abstracted in PHP to \r\n character sequence.”

        Can you help me incorporate this into your form?

  43. I am currently working with a slideshow using jquery-1.4.min.js…………
    while working with the contact php jquery
    jquery-1.2.6.min.js it messes up the slidehow I cant seem to make them both work together….

    can u help?

    1. Can you share us the URL to the page when you’re having this problem? I would like to inspect it. I am sorry for this inconvenience.

      1. I just realized after playing it with couple of times this form is just not compatible with jquery-1.4.2. Do you know how to fix this?? Or it is not made for new version for of JQUERY?

  44. Hi,

    I use jquery latest version jquery-1.4.2 and everytime I click Submit button the javascript popup “Success” will come out. I change back to jquery-1.2.6 and the popup is gone.

    What happen I thought jquery-1.4.2 is compatible with existing version?

    Thanks

    1. You’re probably using an application that is in conflict with either the contact script or it is not compatible with jquery-1.4.2. Can you share us the URL to the page where you noticed this bug?

      1. My apology. I have test this script this weekend with jquery-1.4.2.min.js and it’s works nicely.

        not sure what happen though.

        Thank you :)

  45. I have the premium version and I love it. The only caveat though is that the subject is always pulling in the subject field. The documentation shows where to change the value to ‘true’ for a custom subject field. BUT, I don’t know where to define that custom subject field.

    Please advise. If the documentation has been updated, please let me know. I purchased the premium version about a month and a half ago.

  46. I just used your script on my site: http://www.erikrp.com/contact.htm

    When an email an is sent successfully, I can’t get the form to refresh (with empty content).

    Can anyone help me?

    Many thanks.

    Erik

  47. I just figured it out! Thanks, anyway!

    Tell me your thoughts everyone about my form! Love your input.

    Erik

  48. Hello.

    I have purchased your premium version. I uploaded your form and got error messages. I haven’t changed anything except entering the webmaster email in common.php.

    Here is one error message that I got.
    include_once(../../../ajax-contact-form-premium-script-developer-license/vertical-labels-layout/contact-app/libraries/php.mailer/class.phpmailer.php5.php) [function.include-once]: failed to open stream: No such file or directory in /data/19/1/7/9/1985824/user/2170139/htdocs/testing2/ajax-contact-form/vertical-labels-layout/contact-app/parse2.php on line 16

    I followed your instruction and didn’t find any information on how to correct this.

    BTW, some of your instruction (help/index.html) do not match with your code.

    For example, there is no such stylesheet.css. Just minor issue.

    Anyway, thanks a lot for a great form and help in advance.

    1. I was able to configure the above errors.
      I have another question.

      How can I add checkboxes and radio groups into $formFields?

  49. 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??


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;)