Easy Captcha Setup Using jQuery/AJAX/PHP

Sam Deering
Tweet

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("<p class="green bold">Success! Thanks you may now proceed.</p>");
	} else {
		$("#captcha-status").html("<p class="red bold">The security code you entered did not match. Please try again.</p>");
		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

<!-- terms and conditions checkbox -->
I agree to the terms-and-conditions Terms and Conditions <input type="checkbox" id="termsckb" name="termsckb" />
<!-- the captcha div -->
<div id="captcha-wrap">
	<p>Type in the words below (separated by a space):</p>
	< ?php require_once("phpfunc-showcaptcha.php"); ?>
	<!-- show the captcha result - fail/pass -->
	<div id="captcha-status"></div>
</div>		

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.

<!-- theme options: white, red, blackglass, clean -->
 <script type="text/javascript">
 var RecaptchaOptions = {
    theme : 'theme_name'
 };
 </script>

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

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • Pingback: Easy Captcha Setup Using jQuery/AJAX/PHP « Big Engine Media

  • ARIF MAHMUD RANA

    Does the Google’s reCaptcha work with submodal like facebox or other iframe popups ?

  • http://www.mathdaitechnology.in Aadil hussain

    on submit of form the code won’t work
    help me out

  • ice

    what if someone send post data directly to php file :)
    how will you check the captcha is valid? or even sent? :)

  • Pingback: 10 Cool jQuery with PHP Plugins | jQuery4u

  • Fonzie

    Who have problems, replace:
    data: “form=signup&recaptcha_challenge_field=” + challengeField + “&recaptcha_response_field=” + responseField,

    for:

    data:{form:”signup”,recaptcha_challenge_field:challengeField, recaptcha_response_field:responseField},

    • vince

      you are referring on what problem?. My problem is that i always got a fail message. even if i got it right.

  • Angga Dwi Pratama

    Thanks aloot.. for Sam Deering..
    now i can make ajax form with recaptcha inside my wordpress website..
    your daamn good man..
    thanks..

  • VBR

    Thank you very much..
    It is working for my site

    • vince

      what your site?

  • vince

    hi i always got a fail even if i got the captcha right.

  • Karan Yadav

    Sorry, Friend Big Issue in this Script…
    If You write first Word correct but if You write second Word Wrong So, Success …? Why …? I not write 2 Word Correct.

  • Kamlesh Chauhan

    Sam… It’s wonderful article … working perfectly … thanks.

    I have just one query!

    At this time form submitted after click submit button twice.. once when entered captcha code and second one after captcha code entered correctly. Could we submit the field form by single click of submit button if captcha code entered correctly?