This tutorial, or should I say example, is a very Simple Ajax Contact Form. But don’t let the simplicity fool you. This form can communicate with a PHP Mail Script without having to refresh the page, validate user input on both the client and server sides, work even if the user has JavaScript disabled and will use a nifty little trick to combat Spam.
Nothing in this tutorial is truly original or developed by myself. I’ve compiled the ideas and concepts that I use whenever I need an Ajax Form. I am not claiming creative recognition or ownership of these ideas, and I (try to) give full credit to the original authors of each. I simply hope to provide a resource that some may find useful.
Here’s a demo to check out.
The Ajax part of this tutorial will be handled by MooTools (my favorite JavaScript Library) and will expand upon the Ajax Form presented in their demo section.
Ro Scripts’ AJAX Contact Form is the major source of this form’s inspiration. This is the best tutorial for creating an Ajax Form I’ve found so far, and I highly recommend giving it a read through. Dustin Diaz’s Ajax Contact Form is also interesting and worth checking out.
The client side form validation is handled by Fabio Zendhi Nagao’s fValidator, which also uses MooTools. This script is very well documented, so if you need help with it, check out the usage and examples.
The HTML Form
A pretty basic HTML Form. Be sure to take note of the ID and Class names on the Form, Inputs and in one instance an Li tag. You can lay out your Form anyway you’re comfortable with, but you’ll soon see why having each Label/Input nested in an Li tag proves useful.
The Div ‘log’ is used to display messages from the PHP Script, and ‘log-res’ will be used to show an Animated GIF image while the form is being processed. For Loading Animated GIFs, check out Ajax Load.
<form action="send.php" method="post" id="myForm" class="fValidator-form"> <fieldset> <ol> <li> <label for="firstName">First Name</label> <input name="firstName" id="myForm_firstName" class="fValidate['required']" type="text" value="" /> </li> <li> <label for="lastName">Last Name</label> <input name="lastName" id="myForm_lastName" class="fValidate['required']" type="text" value="" /> </li> <li> <label for="Email">E-Mail</label> <input name="Email" id="myForm_Email" class="fValidate['required','email']" type="text" value="" /> </li> <li class="human"> <label for="subject">Subject</label> <input name="subject" id="myForm_subject" type="text" value="" /> </li> <li> <label for="message">Message</label> <textarea name="message" id="myForm_message" class="fValidate['required']" rows="5" cols="20"></textarea> </li> </ol> </fieldset> <p><input type="submit" name="button" id="myForm_submit" value="Send" /><input type="reset" value="Reset" /></p> <div id="log"> <div id="log_res"> <!-- spanner --> </div> </div> </form>
The PHP Script
This is a slightly modified version of the PHP Mail Script Ro Scripts’ AJAX Contact Form is using. If you need an explanation, check their tutorial.
<?php error_reporting(E_ALL); function valid_email($str) { return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE; } if($_POST['subject']!=""){ echo 'Dirty Spammer! Your message was NOT sent.'; } else { if( isset($_POST['firstName']) && isset($_POST['lastName']) && isset($_POST['Email']) && valid_email($_POST['Email'])==TRUE && isset($_POST['message']) && strlen($_POST['message'])>15) { $to = 'you@youremail.com'; $headers = 'From: '.$_POST['Email'].''. "\r\n" . 'Reply-To: '.$_POST['Email'].'' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); $subject = "Your Simple AJAX Contact Form"; $message = htmlspecialchars($_POST['message']); $spam = $_POST['subject']; if(mail($to, $subject, $message, $headers)) {//we show the good guy only in one case and the bad one for the rest. echo 'Thank you '.$_POST['firstName'].'. Your message was sent.'; echo '<noscript> <a href="http://www.yourdomain.com">Back to yourdomain.com</a></noscript>'; } else { echo "Message not sent."; echo "Please make sure you're not running this on localhost and also that you are allowed to run mail() function from your webserver."; } } else { echo "Please make sure you filled in all the required fields, that you entered a valid email and also that your message contains more then 15 characters."; echo "<noscript> Use your browser's back button or <a href=\"http://www.yourdomain.com\">click here</a></noscript> to try again."; } } ?>
Loading MooTools and fValidator
Just before the closing Head tag, you need to call MooTools, fValidator and insert the proper JavaScript to tell fValidator and MooTools what to do with your form.
<script type="text/javascript" src="mootools.js"></script> <script type="text/javascript" src="fValidator.js"></script> <script type="text/javascript"> //<![CDATA[ window.addEvent('domready', function(){ // fValidator var myFormValidator = new fValidator('myForm'); // AJAX Form $('myForm').addEvent('submit', function(e) { if(myFormValidator._onSubmit(e)){ new Event(e).stop(); var log = $('log_res').empty().addClass('ajax-loading'); this.send({ update: log, onComplete: function() { log.removeClass('ajax-loading'); } }); } }); // Reset $('myForm').addEvent('reset', function(e) { var log = $('log_res').empty(); }); }); //]]> </script> </head>
Non-JavaScript Functionality
You may notice that the PHP Script checks for valid input. The user’s email is checked using a PHP Regular Expression in the Function valid_email($str). The other inputs can be anything really, so isset($_POST['']) is used with the addition of strlen($_POST['message'])>15) added, to check for the amount of characters in the message. The value 15 is used, but feel free to change this to suit your needs.
These simple checks ensure that if users have JavaScript disabled, our form will still be validated. However, instead of the message being displayed via Ajax on our form page, users will be taken to blank white page with the message displayed.
Then, using the noscript tag, we can insert some code that only Non-JavaScript users will see. In this case, I kept it simple, and only included directions on which actions to take.
Particle Tree’s Degradable Ajax Form Validation may be useful if you’d like to extend beyond this basic functionality. Ro Scripts also has a good article about Unobtrusive Ajax/PHP form validation.
Combatting Spam
I’m not sure where I ran across this little nugget, but it has proven invaluable. Looking back at our HTML Form, you may remember being reminded to take note of one Li instance. I was referring to the Li tag with the Class ‘human’. Using CSS, I’ve hidden this Li from view - visibility: hidden; . Essentially making the filling out of this field impossible. Unless of course you’re a Spam Bot. A Spam Bot will fill out our Inputs based on their Names. I named our Spam Blocking Input ’subject’.
<li class="human"> <label for="subject">Subject</label> <input name="subject" id="myForm_subject" type="text" value="" /> </li>
Here’s the CSS File used.
Now look at the following PHP:
if($_POST['subject']!=""){ echo 'Dirty Spammer! Your message was NOT sent.'; } else {
In plain English: if the Input named ’subject’ is filled with anything, a message to the Spammer is given, and the Form is not sent. If the ’subject’ Input is NOT filled with anything, our PHP Script runs as it should.
Give it a try, fill out the Form Fields correctly, with and without the ’subject’ Input.
AlexM
August 13th, 2008
I found your site on technorati and read a few of your other posts. Keep up the good work. I just added your RSS feed to my Google News Reader. Looking forward to reading more from you down the road!
Jono Alderson
August 16th, 2008
Thanks - best ajax contact form script on the net, without a doubt.