How to make AJAX “Contact us” page template with Recaptcha for wordpress

As some of our frequent readers know I`m working as a wordpress developer and support for many sites, and I`ve used countless wordpress plugins for contact forms but I`ve never found one that fits my needs completely. The most important feature of “Contact us” plugins is reliability, and because of my recent disappointment of Contact Form 7 plugin I decided to write a wordpress tutorial about creating an AJAX based one. When I started developing I decided that the most appropriate format for me is not a plugin, but a wordpress page template. I`ve mentioned wordpress page templates before(here), so if any of you is unfamiliar it will be a good idea to go through that article first.

I`ll upload the files for twentyeleven. Of course you can easily adjust them for any theme(if any of you is facing problems with that either write in the comments section, or you can contact me here).

You`ll have to register for reCaptcha`s keys on recaptcha`s site – http://www.google.com/recaptcha/whyrecaptcha

Page-contact.php

You must insert the public key you got from registering in recaptcha`s site on Line: 36


<?php /*

Template Name: Contact us

*/

get_header(); ?>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.21/themes/ui-darkness/jquery-ui.css" type="text/css" media="screen">
<!-- mid content -->
<div id="main">
<div id="primary" style="background-color:#fff">
<div id="content" role="main">
<article id="post" class="post no-results not-found">
<h1 class="entry-title">Contact us</h1>
<div id="errors"></div>
<form>
<p>
Message subject *
<br>
<input type="text" name="subject" id="subject" size="35"/>
</p>
<p>
Reply e-mail *
<br>
<input type="text" name="email" id="email" size="35"/>
</p>
<p>
Body *
<br>
<textarea id="body" cols="45" rows="5"></textarea>
</p>
<?php
require_once('recaptchalib.php');
$publickey = "INSERT YOUR PUBLIC KEY HERE"; // you got this from recaptcha signup page
echo recaptcha_get_html($publickey);
?>
<p>
<input type="submit" value="Submit" id="submit" />
</p>
</form>
</article>
</div>
</div>
</div>
<!-- mid content -->
</div>
<!-- /mid -->

<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.js" type="text/javascript"></script>
<script>
$(function() {
$('#submit').click(function() {
$.post("<?php echo get_bloginfo('template_directory'); ?>/contact-us.php", { subject: $('#subject').val(), email: $('#email').val(), body: $('#body').val(), recaptcha_challenge_field: $('#recaptcha_challenge_field').val(), recaptcha_response_field: $('#recaptcha_response_field').val() },
function(data){
var $errors = null;
var $errors = data.errors;
var $recaptcha = null;
var $recaptcha = data.recaptcha;
var $success = null;
var $success = data.success;
if(data.errors) {
$dialog = $('<div style="font-size:20px;padding-left: 10px;"></div>')
.html('Please fill in '+$errors)
.dialog({
autoOpen: false,
title: '<span id="test">Error!</span>',
modal: true,
width: 365,
minHeight: 95,

});
$dialog.dialog('open');
}
else if(data.recaptcha){
$dialog = $('<div style="font-size:20px;padding-left: 10px;"></div>')
.html($recaptcha)
.dialog({
autoOpen: false,
title: '<span id="test">Error!</span>',
modal: true,
width: 365,
minHeight: 95,
close: function() {
Recaptcha.reload();
}
});
$dialog.dialog('open');
}
else if(data.success){
$dialog = $('<div style="font-size:20px;padding-left: 10px;"></div>')
.html($success)
.dialog({
autoOpen: false,
title: '<span id="test">Yey!</span>',
modal: true,
width: 365,
minHeight: 95,

});
$dialog.dialog('open');
}
else {
$dialog = $('<div style="font-size:20px;padding-left: 10px;"></div>')
.html('Thanks for submitting your interest!')
.dialog({
autoOpen: false,
title: '<span id="test">Form submission</span>',
modal: true,
width: 365,
minHeight: 95,

});
$dialog.dialog('open');
}
console.log(data.errors);
}, "json");
return false;
});
});
</script>
<?php get_footer(); ?>

Contact-us.php

Insert the private key got you got from registering in recaptcha`s site on Line: 9

Insert the address to which you want the mails send on Line: 58

Insert the address from which you want the mails received on Line: 59


<?php
$subject = $_POST['subject'];
$email = $_POST['email'];
$body = $_POST['body'];
$recaptcha_challenge_field = $_POST['recaptcha_challenge_field'];
$recaptcha_response_field = $_POST['recaptcha_response_field'];
//Re-Captcha
require_once('recaptchalib.php');
$privatekey = "INSERT YOUR PRIVATE KEY HERE";
$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
$json_array['recaptcha'] ="The reCAPTCHA wasn't entered correctly. Go back and try it again."."(reCAPTCHA said: " . $resp->error . ")";
echo json_encode($json_array);
} else {
 $json_array = array();
 $errors = '';
 if(empty($subject))
 {
 $errors .= ' Subject ';
 }
 if(empty($email))
 {
 $errors .= ' Email ';
 }
 if(empty($body))
 {
 $errors .= ' Body ';
 }
 if(empty($recaptcha_response_field))
 {
 $errors .= ' Captcha ';
 }

$elements = explode(" ", $errors);

switch (count($elements)) {
 case 1:
 $errors = $elements[0];
 break;
 case 2:
 $errors = $elements[0].' and '.$elements[1];
 break;
 case 3:
 $errors = $elements[0].', '.$elements[1].' and '.$elements[2];
 break;
 case 4:
 $errors = $elements[0].', '.$elements[1].', '.$elements[2].' and '.$elements[3];
 break;
 }
 if(!empty($errors))
 {
 $json_array['errors'] = $errors;
 echo json_encode($json_array);
 }
 else
 {
 $to = 'Insert the address to which you want the mails send';
 $headers = 'From: Insert the address from which you want the mails received' . "\r\n" .
 'Reply-To: '.$email. "\r\n" .
 'X-Mailer: PHP/' . phpversion();
 mail($to, $subject, $body, $headers);
 $json_array['success'] = "Thanks for contacting us!";
 echo json_encode($json_array);
 }
}

?>

Recaptcha lib can be downloaded here

You can download an archive with the files below. You must extract it in your theme`s folder and follow the instructions above to set it up. If some of you are interested in plugin with that functionality use the comment section below and I`ll see what I can do.

  • chronoforms recaptcha

    I want to to thank you for this very good read!! I absolutely loved every little bit of it.
    I have got you book-marked to check out new things you
    post…