In this tutorial I am going to teach you how to create an Ajax contact form for your website. The main purpose of using ajax for this task will be the fact that you’re saving bandwidth (hard to believe that in 2007 we’re still looking to save bandwidth but…), it communicates with the visitor on the same page, almost instantly and is faster because you’re not loading another page to show a confirmation message or whatever else is supposed to show given the situations.
- Check out new Php Regular Expressions.
There are many ways of doing this, we’re going to use mootools to make AJAX possible. Mootools is a lightweight javascript library developed by Valerio Proietti and is capable of creating a huge amount of effects. The advantage on mootools is that you don’t need to download the whole library just to have an ajax event or some other tiny effect. You just download what you need.
Ok, now that we finished introducing our tools let’s start coding. Our small project will contain 4 files: mootools, a stylesheet and our index page (interface) which will be working with send.php with the help of ajax. Basically, we have our main page helped by some AJAX magic to send data and receive+display the response. Our php code will look like an ordinary PHP mailer, using the mail() function:
<?php error_reporting(E_NOTICE); 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['first_name']!='' && $_POST['last_name']!='' && $_POST['e_mail']!='' && valid_email($_POST['e_mail'])==TRUE && strlen($_POST['message'])>30) { $to = '[email protected]'; $headers = 'From: '.$_POST['e_mail'].'' "\r\n" . 'Reply-To: '.$_POST['e_mail'].'' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); $subject = "Hello! I'm testing my new ajax email that I got from roscripts.com"; $message = htmlspecialchars($_POST['message']); 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['first_name'].'. Your message was sent'; } else { echo "Message not sent. 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 all the required fields, that you entered a valid email and also that your message contains more then 30 characters.'; } ?>
Analyzing the code you will notice the function (which was taken from our snippets section) “valid_email” that we will use to validate the email address of the visitor. Also, I’ve started the code using an if statement to make sure all fields are completed, the message is bigger then 30 characters (you can modify everything to match your needs) and that the sender’s email address is a valid one. Please notice that I used htmlspecialchars() to avoid any attempt of cross site scripting(XSS) which is hard to believe that will bypass any email client at this moment but it’s always good to be prepared and cover anything that might be vulnerable.
The javascript code which will trigger the event and process our form is very small and easy to follow. It’s ready to run on domready which is way much faster than onLoad and it uses Fx.Elements to change the class of our receiver element (<div id=”log”>) in order to show a loading gif until the job is done and our php sends back the response which can either be a positive one or negative.
window.addEvent('domready', function(){ $('myForm').addEvent('submit', function(e) { new Event(e).stop(); var log = $('log_res').empty().addClass('ajax-loading'); this.send({ update: log, onComplete: function() { log.removeClass('ajax-loading'); } }); }); });
I have created a fully functional Ajax contact form available for you to download and use right away (download link lower on the page). Please make sure you’re allowed to use the mail() function and also, your server has PHP installed.
Here’s a demo of our application (it won’t send out any emails).