Press enter to see results or esc to cancel.

Load Error Message Using Google’s Recaptcha With Ajax API

I recently began using Google’s reCaptcha plugin on a client’s site to reduce spam submissions on one of their forms – something the plugin does wonderfully.

What is captcha? From the google.com/recaptcha website:

A CAPTCHA is a program that can tell whether its user is a human or a computer. You’ve probably seen them — colorful images with distorted text at the bottom of Web registration forms. CAPTCHAs are used by many websites to prevent abuse from “bots,” or automated programs usually written to generate spam. No computer program can read distorted text as well as humans can, so bots cannot navigate sites protected by CAPTCHAs.

To implement a solution for my client’s problem, I programmed against reCaptcha’s Ajax API because my client’s form uses Ajax to submit content. In order to figure out how reCaptcha works with Ajax, I referred to the Ajax API documentation on reCaptcha’s website.

On the page where the client’s form is found I included a reference to recaptcha_ajax.js script (which is found on reCaptcha’s site_ and I called Recaptcha.create with appropriate parameters passed in from my $(document).ready jquery call. Upon Ajax submit of the form I passed along the challenge and response field values as well as the user’s ip address and then verified the data against http://www.google.com/recaptcha/api/verify as described in the above mentioned docs.

This is where I ran into a problem. Upon invalid submission, I was unable to get reCaptcha to display it’s default inline errors to the user – something that is quite easily done with the non-Ajax versions of reCaptcha by simply attaching “&error=incorrect-captcha-sol” to the end of the challenge request url.

A couple of people have attempted to find a solution to this problem. Brandon Turner provides a hack to change the reCaptcha’s widget css class based on the error reCaptcha generates. Techenabled displays a custom error and avoids using the inbuilt reCaptcha functionality altogether. I didn’t like either solution to be honest because I wanted to use the inbuilt functionality and I didn’t want to rely on css classes which might change in the future.

Instead, here is what I came up with.

When you call reCaptcha API verify method, you get 2 lines of response. Line 1 gives you true or false – true meaning the captcha response was valid. Line 2 gives you the error message incase line 1 returned false. My server-side code returns an empty string if response was true (valid) and returns the error code (line 2 of response) if response was false.

So, instead of playing around with css classes or displaying custom errors, inside my ajax call’s success handler, I do the following:

            
success: function (msg) {
    if (!msg || !msg.d || msg.d.length == 0) {
        $("#captchadiv").hide(); // hide the captchadiv element since all is ok
    } else {
        createRecaptcha(msg.d); // call createRecaptcha function with error message passed in...
    }
}

And the createRecaptcha() method looks like this:

function createRecaptcha(error) {
    var errorString = '';
    if (error != null && error.length > 0)
        errorString += "&error=" + error;
    
    var RecaptchaOptions = {
        tabindex: 1,
        theme: "red",
        callback: Recaptcha.focus_response_field
    };
    Recaptcha.create("my public key" + errorString, 'captchadiv', RecaptchaOptions);
}

What is it that the code does?

Well, as described in the non ajax API documentation, in order to get reCaptcha to display the internal error message, we have to attach “&error=incorrect-captcha-sol” to the end of the challenge request url. By attaching “&error=” + errorString above to my public key, this is achieved quite nicely since the public key is attached to the challenge request url inside the Recaptcha.create method.

Works a treat!

Sidenote: interestingly, Google’s reCaptcha plugin helps digitize books – by using the text recognition done by humans to decipher scanned pages of paperback books – currently, Google is helping to digitize old editions of the New York Times and books from Google Books.

Comments

3 Comments

java guy

dude.. you the man….. i was struggling with this issue in my gwt project…
now works like a charm…thanks bro..

Mirza

Cheers mate. I am glad I helped you out.

Mauricio Lima

Hi, great post!

There is an extra option you can pass on:

Recaptcha.create(your_public_key, element, {
callback: Recaptcha.focus_response_field,
extra_challenge_params: ‘&error=’ + errorMessage
});


Leave a Comment