In this tutorial we are going to create a Simple Contact form using jQuery, AJAX, PHP and reCAPTCHA to prevent spam. So why use AJAX?. AJAX does not require page reloads when user submits a form. When user clicks Submit button Email is sent instantly without page reloads. This makes the process easy and fast. We are going to learn how to make HTML Contact form with AJAX, jQuery Data validation and reCAPTCHA. reCAPTCHA effectively protects against spam and prevent abuse of contact form.
If you are a bit familiar with HTML, PHP, jQuery then understanding this tutorial will be much easier. Here is how our form will look like after completion.
Configuration File:
reCAPTCHA can be enabled/disabled from this file. Please enter private key and public key before turning on reCAPTCHA. Get your reCAPTCHA keys from here.
1 2 3 4 5 6 7 8 |
<?PHP // Turn recaptcha on or off $recaptcha_status = TRUE; // FALSE for off & TRUE for on if($recaptcha_status){ $privatekey = "Enter Private Key Here"; $publickey = "Enter Public Key Here"; require_once('recaptchalib.php'); } |
HTML MARK UP:
Let’s start with writing HTML of the contact form. HTML contains Name, Email & Message Input fields. You can add check boxes, radio buttons as per your requirement. You might have noticed that we have not wrapped our fields with <form> </form> tags. This is because we do not need them as we are using jQuery .val() function to get values and using AJAX to post them to our server.
I have included reCAPTCHA code just after message field in this form also. If reCAPTCHA is enabled in config.php then it will show up and reCAPTCHA validation will also be performed server side via AJAX.
Submit button triggers the jQuery code which will collect all values and post data to contact.php with AJAX.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<div id="result"></div> <div id="frmbox"> <fieldset id="contact_form"> <legend>My Contact Form</legend> <label><span>Name: </span><input placeholder="Your Name" name="user" type="text" required="required" /></label> <label><span>Email: </span><input placeholder="[email protected]" name="em" type="email" required="required" /></label> <label><span>Message: </span><textarea name="msg"></textarea></label> <?PHP if($recaptcha_status){ echo recaptcha_get_html($publickey); } ?> <br /><span style="float:left;clear:both;padding: 5px 0 0 0; "><input name="st" id="st" type="button" value="Submit" /> <span id="loading"><img src="loading.gif" /></span></span> </fieldset> </div> |
CSS:
You can style your form as you require. I have already applied some styling to the form. It is included in <head> section. You can alter or create new one.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#frmbox { position:relative;margin:50px auto; width:400px;min-height:200px;z-index:100;padding:30px;border:1px solid #383838; border-radius:8px;box-shadow:0px 1px 6px #3F3F3F;} #frmbox:after{margin:10px;position: absolute;content : " ";bottom: 0;left: 0;right: 0;top: 0;z-index: -1;border:1px #E5E5E5 solid; border-radius:8px;} #frmbox legend{font-size: 15px; color: #428bca;} #frmbox label{display: block; margin-bottom:5px;} #frmbox label span{margin: 8px 0 0 4px;float:left; width:100px; color:#666666; } #frmbox input{height: 25px; border: 1px solid #DBDBDB; border-radius: 3px; padding-left: 4px; color: #666; width: 180px; font-family: Arial, Helvetica, sans-serif;} #frmbox textarea{border: 1px solid #DBDBDB; border-radius: 3px; padding-left: 4px;color: #666; height:100px; width: 180px; font-family: Arial, Helvetica, sans-serif;} #frmbox input:focus,textarea:focus{border-color: #9ecaed;box-shadow: 0 0 10px #9ecaed;outline: medium none; } #loading { display: none;} .submit_btn { border: 1px solid #D8D8D8; padding: 5px 15px 5px 15px; color: #8D8D8D; text-shadow: 1px 1px 1px #FFF; border-radius: 3px; background: #F8F8F8;} .submit_btn:hover { background: #ECECEC;} .success{-webkit-box-shadow:5px 5px 8px 8px #B0B0B0; box-shadow:5px 5px 8px 8px #B0B0B0; background: none repeat scroll 0 0 #eeeeee;border: 1px solid #888888;border-radius: 12px; font-weight: normal;margin-bottom: 10px;padding: 10px; } .fail{-webkit-box-shadow:5px 5px 8px 8px #FFCEBD; box-shadow:5px 5px 8px 8px #FFCEBD; background: none repeat scroll 0 0 #FF928A;border: 1px solid #FF928A;border-radius: 12px; font-weight: normal;margin-bottom: 10px;padding: 10px; } |
jQuery AJAX:
Now we will write jQuery code to make AJAX calls. We will use $(document).ready() jQuery function. It means all jQuery code written in $(document).ready() will only work after page loading is complete.
In $(document).ready() function there is $(“#st”).click. #st is submit button id attached to .click JavaScript event. Clicking submit button triggers an event and all jQuery code in $(“#st”).click is executed.
.val() is used to collect input field data and $.post send data to contact.php using AJAX.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
$( document ).ready(function() { $("#st").click(function() { //get input field values var user_name = $('input[name=user]').val(); var user_email = $('input[name=em]').val(); var user_message = $('textarea[name=msg]').val(); var challengeField = $("input#recaptcha_challenge_field").val(); var responseField = $("input#recaptcha_response_field").val(); //data to be sent to server post_data = {'user':user_name, 'email':user_email, 'msg':user_message, 'recaptcha_challenge_field': challengeField, 'recaptcha_response_field': responseField}; document.getElementById("loading").style.display="inline-block"; //Ajax post data to server $.post('contact.php', post_data, function(response){ //load json data from server and output message if(response.type == 'error') { output = '<div class="fail">'+response.text+'</div>'; }else{ output = '<div class="success">'+response.text+'</div>'; } document.getElementById("loading").style.display="none"; $("#result").hide().html(output).fadeIn(); $("#frmbox").fadeOut("slow"); //reset values in all input fields $(function() { setTimeout(function() { $('input[name=user]').val(''); $('input[name=em]').val(''); $('textarea[name=msg]').val(''); }, 1); }); }, 'json'); }); }); |
contact.php:
AJAX requests are processed to contact.php, this file sends email to the recipient and responds back to the AJAX request in case of success or failure.
This file is simple and self explanatory. But I will briefly describe its working. This file receives POST data from contact form. Then reCAPTCHA is validated if enabled. Now POST data are sanitized using filter_var() function, after that we validate data server-side for security. Now PHP Mail is sent and json_encode is used to return success or error message which is then parsed by jQuery and shown to the user.
An error message is returned by file if reCAPTCHA is not validated or POST data is not validated or email is not sent.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 |
<?php require_once('config.php'); if($_POST) { $pass = TRUE; if($recaptcha_status){ if(isset($_POST["recaptcha_challenge_field"])){ $resp = recaptcha_check_answer ($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]); if (!$resp->is_valid) { // What happens when the CAPTCHA was entered incorrectly //output error info $output = json_encode( array( 'type'=>'error', 'text' => 'The reCAPTCHA wasn\'t entered correctly.<a href="#" onclick="back()">(Return)</a>' )); die($output); $pass = FALSE; } } } if($pass){ //Recipient email address //Subject line for emails $subject = 'Someone contacted using contact page on my-website.com ...'; //Check if its an AJAX Request, else return error if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') { //output error info $output = json_encode( array( 'type'=>'error', 'text' => 'Direct Access not allowed. AJAX Requests permitted.' )); die($output); } //check $_POST vars are set, exit if any missing if(!isset($_POST["user"]) || !isset($_POST["email"]) || !isset($_POST["msg"])) { $output = json_encode(array('type'=>'error', 'text' => 'Input fields are empty!')); die($output); } //Sanitize input data using PHP filter_var(). $name = filter_var($_POST["user"], FILTER_SANITIZE_STRING); $email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL); $message = filter_var($_POST["msg"], FILTER_SANITIZE_STRING); //additional php validation if(strlen($name) < 2) // If length is less than 3 it will throw an HTTP error. { $output = json_encode( array('type'=>'error', 'text' => 'Name is too short or empty!<a href="#" onclick="back()">(Return)</a>')); die($output); } if(!filter_var($email, FILTER_VALIDATE_EMAIL)) //Validate Email { $output = json_encode(array('type'=>'error', 'text' => 'Enter a Valid Email Address! <a href="#" onclick="back()">(Return)</a>')); die($output); } if(strlen($message) < 1 ) //Enter a message { $output = json_encode(array('type'=>'error', 'text' => 'Too short message! Please enter something.<a href="#" onclick="back()">(Return)</a>')); die($output); } //Now send email using PHP Mail function /* If your webhost only allows emails from local domain, then un-comment the first line below, and comment the second header line. In the first line enter your own email address here, created in your cp. */ //$headers = 'From: [email protected]' . "\r\n" . $headers = 'From: '.$email.'' . "\r\n" . //remove this line if line above this is un-commented 'Reply-To: '.$email.'' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); // PHP send email function $email_sent = @mail($recipient, $subject, $message .'\n Sender Name:'.$name, $headers); /* if any error occures while sending email and you are unable to find it. Remove @ from @mail in above line. It will show you exact error. */ if(!$email_sent) { $output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.')); die($output); }else{ $output = json_encode(array('type'=>'message', 'text' => 'Hi '.$name .' Your Email has been sent successfully.. <a href="#" onclick="back()">(Return)</a>')); die($output); } } } ?> |
So this is it! Now you can integrate this form to your website, don’t forget to include jQuery into the contact form page or download complete files for easy integration.
Thanks, for this awesome tutorial, now exist to recatcha v2. but is a nice tutorial 🙂