11

I trying to implement reCAPTCHA in one of my forms,...but i am using ajax as the submission. (More specifically the prototype ajax.updater)

Once I submit and error check my form I try to load the reCAPCHTA widget thingy (in my updated div element) which basically just calls a javascript file like so:

<script type="text/javascript" src="http://api.recaptcha.net/challenge?k=6Le6SwUAAAAAAIWm8wCRFd8SrI-H0R1Yx4Tkw2Ks"></script>

However the JS file is not being read?...and i've tried all combination of evalScripts:true and evalJS:'force' etc. in the ajax.updater.....however i don't think I have a very good understanding of why the js file isn't processing :(

If anyone can shed some light on this issue I will be very appreciative.

Thanks, Andrew

Rob W
  • 341,306
  • 83
  • 791
  • 678
Andrew
  • 3,650
  • 9
  • 31
  • 32

8 Answers8

17

This doesn't address your exact problem, but 'Dark Side of the Carton' has some excellent code for validating reCAPTCHA via jQuery AJAX which might help.

In summary:

Add the following Javascript:

$(function() {
    function validateCaptcha() {
        var challengeField = $('input#recaptcha_challenge_field').val(),
            responseField  = $('input#recaptcha_response_field').val();

        // alert(challengeField);
        // alert(responseField);
        // return false;

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

        if (html.replace(/^\s+|\s+$/, '') == "success") {
            $('#captchaStatus').html(' ');
            // Uncomment the following line in your application
            return true;
        } else {
            $('#captchaStatus').html(
                'Your captcha is incorrect. Please try again'
            );
            Recaptcha.reload();
            return false;
        }
    }

    // Modified as per comments in site to handle event unobtrusively
    $('#signup').submit(function() {
        return validateCaptcha();
    });
});

Then add the ajax.recaptcha.php file which: "outputs only the word “success” if the captcha matches and a message and the response from reCaptchta if it fails. This is important because we are looking for the word success in our validateCaptcha() function."

require_once('/inc/recaptchalib.php');
$publickey  = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX'; // you got this from the signup page
$privatekey = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX';

$resp = recaptcha_check_answer(
    $privatekey,
    $_SERVER['REMOTE_ADDR'],
    $_POST['recaptcha_challenge_field'],
    $_POST['recaptcha_response_field']
);

if ($resp->is_valid) {
    ?>success< ?
} else {
    die(
        "The reCAPTCHA wasn't entered correctly. Go back and try it again." .
        "(reCAPTCHA said: " . $resp->error . ")"
    );
}

The example is in PHP, but I adapted it easily to work with Zope/Python

Yes Barry
  • 9,514
  • 5
  • 50
  • 69
Jon Hadley
  • 5,196
  • 8
  • 41
  • 65
  • Hmm, you should store the result of the validation in the session, as one might just skip the validateCaptcha call and submit the form without solving the captcha. Also remember to reset it in the session after performing the captcha protected action, so one solution can't be used multiple times. – iGEL Jul 13 '12 at 13:13
  • For some reason, I was getting an undefined index for `$_POST["recaptcha_challenge_field"]` until I rewrote the data setting in the ajax call with JSON. – regularmike Apr 30 '13 at 18:14
  • ajax data should be: `data: "recaptcha_challenge_field=" + challengeField + "&recaptcha_response_field=" + responseField,` not `&` – Vaibhav Gupta Jan 28 '14 at 17:54
4

Be careful using any sort of client-side script, such as JavaScript, for validation. You have no control over the end-user's browser. The purpose of a CAPTCHA is to prevent automated submissions of a form. Anyone sophisticated enough to set that up isn't going to have a problem overriding your JavaScript validation and CAPTCHA checking. For example, they could set validateCaptcha() to always return true, bypassing your careful checks - or just disable JavaScript.

That being said, there's nothing wrong with performing the entire form submission with ajax and using the results of the CAPTCHA check to determine if the form gets processed or not.

The important point is that the decision of whether or not to handle the form has to be made on the server-side, not the client-side.

Why client-side validation is not enough

Community
  • 1
  • 1
dillon
  • 41
  • 2
  • Right, you would also want to do the server-side check. But the client-side validation is useful so that legitimate visitors can get feedback without losing their entire form submission when they accidentally type the words incorrectly. Some of the captcha challenges can be difficult. – regularmike Apr 30 '13 at 14:05
1

to answer my own question...

there is a reCAPTCHA AJAX api....which is pretty easy way to get around this problem:

link text

Also,..the documentation on the http://www.prototypejs.org/api/ajax/updater site.....talks about the evalscript option and how is only puts any javascript through the native eval() function....which kind of screws me over trying to implement error checking with WMD...but that's another story.

Andrew

Andrew
  • 3,650
  • 9
  • 31
  • 32
0

call Recaptcha.reload(); on callback event in your Ajax code., it will reload new Recapcha every time that Ajax submitted

Somwang Souksavatd
  • 4,947
  • 32
  • 30
0

Hi Friend i found the answer

https://developers.google.com/recaptcha/docs/display?hl=es#AJAX

And in this how validate

http://blog.reaccionestudio.com/comprobar-recaptcha-con-ajax-usando-jquery/

Success for you

infinito84
  • 1,971
  • 17
  • 8
  • -1 - You should explain the answer in addition to posting links, so it can be valuable even when the links become invalid. I will remove downvote once you have edited. – Tibos Sep 28 '13 at 07:36
0

If that's the literal code snippet you're using, you haven't closed the tag... so it wouldn't be evaluated.

Matt Howell
  • 15,750
  • 7
  • 49
  • 56
0

Securing AJAX calls with reCaptcha

function performAJAX() {
    let captcha = $('[name=g-recaptcha-response]');
    $.ajax({
         url: 'ajaxHandler.html',
         data: {
            captcha: (captcha.length?captcha[0].value:''),
            // other data fields
         },
    });
}
-1

I have had similar issues with getting reCaptcha to play nicely when loaded into the page using jQuery's .load() method. Here is a page that has a novel solution: http://www.maweki.de/wp/2011/08/recaptcha-inside-a-with-jquery-ajax-or-load-dynamically-loaded-object/

Basically the reCaptcha API uses document.write method to display the reCaptcha. When you get jQuery invloved this won't work. Use this PHP code in place of loading recaptcha.js

<?php
$api = file_get_contents('http://www.google.com/recaptcha/api/js/recaptcha_ajax.js');
$api = str_replace('document.write','$("body").append',$api);
echo $api;
?>

It just does a find for document.write and replaces it with $(selector).append.

Made my implementation work.

Prasad Jadhav
  • 5,090
  • 16
  • 62
  • 80
Aaron
  • 1