Easy Captcha Setup Using jQuery/AJAX/PHP

Sam Deering
Share

recaptcha2

What is a captcha?

These days when you are using forms you need some sort of protection from bots and spammers. One way to reduce spam is to use something called a Captcha – it simple puts a human readable words which the use has to type into a box to prove they are human. There are many free ones out there and I have used a few and found the Google reCaptcha to be pretty easy to install and use.

jQuery Captcha Demo
Download Source Files

  • jquery4ucaptcha.zip
    • showform.php
    • jquerycaptcha.js
    • validateform.php
    • recaptchalib.php

How it works

captcha-diagram

A common problem solved

The user has entered the captcha and got it wrong. Now when they click back they lose all thier form data in the fields they just filled out! Disaster! Fortunately, I’ve come up with a way to send an AJAX request so that no form input data is lost if the captcha is wrong. If the captcha is right the user is simply prompted to submit.

How to setup your form captcha

Step 1. You need to get your own setup keys from Google reCaptcha Website. You will get both a private key and a public key you need both for it to work.

Step 2. Download and save recaptchalib.php.

Step 3. The jQuery Code – jquerycaptcha.js

//Validate the Recaptcha' Before continuing with POST ACTION
function validateCaptcha()
{
	challengeField = $("input#recaptcha_challenge_field").val();
	responseField = $("input#recaptcha_response_field").val();

	var html = $.ajax({
		type: "POST",
		url: "../php/validateform.php",
		data: "form=signup&recaptcha_challenge_field=" + challengeField + "&recaptcha_response_field=" + responseField,
		async: false
		}).responseText;

	//console.log( html );
	if(html == "success") {
		//Add the Action to the Form
		$("form").attr("action", "../php/db-process-form.php");
		$("#submit").attr("value", "Submit");
		//Indicate a Successful Captcha
		$("#captcha-status").html("

Success! Thanks you may now proceed.

"); } else { $("#captcha-status").html("

The security code you entered did not match. Please try again.

"); Recaptcha.reload(); } }

Step 4. The PHP Code1 – validateform.php

require_once("recaptchalib.php");

$privatekey = "[yourprivatekeyhere]";
$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
    echo "fail";
} else {
	echo "success";
}

Step 5. The PHP Code2 – showcaptcha.php

require_once("recaptchalib.php");
$publickey = "[yourpublickeyhere]";
// show the captcha
echo recaptcha_get_html($publickey);

Step 6. The HTML Code


I agree to the terms-and-conditions Terms and Conditions 

Type in the words below (separated by a space):

Step 7. A nice touch
A nice touch would be to hide the Captcha until the user has filled out the form or ticked an agree to terms and conditions button. Here is how you do it.

$(document).ready(function() {
	if ($('input[name=termsckb]').attr('checked') != true) {
		$('#captcha-wrap').hide();
	}

	$('#termsckb').change(function() {
		 if ($('input[name=termsckb]').attr('checked') == true) {
			 $('#captcha-wrap').show();
			 $("#signupbutton").attr("value", "I am human!");
		 }
		 else {
			 $('#captcha-wrap').hide();
			 $("#signupbutton").attr("value", "Submit");
		 }
	});
});

Step 8. Customise the captcha style
You can change the style and colour of the captcha to suit your website. There are 4 different choices on the official site: red, white, black and transparent.


 

See Customizing the Look and Feel of reCAPTCHA for more info. I personally prefer the clear (transparent) option.