Ajax Validation for reCaptcha

时间:2013-04-27 作者:Giraldi

背景我有一个registration form 使用AJAX验证jQuery Validation Engine. 表单是使用创建的Theme My Login 和包含reCaptcha 我使用WP-reCAPTCHA.

就像其他领域一样,我需要validate reCaptcha using AJAX 也就是说,不刷新整个页面。到目前为止,当验证码没有验证时,我成功地使其工作。但是when it did validate, 即,输入正确,页面刷新,但带有error message 上面说\'That reCAPTCHA response was incorrect\'. 因此,表单未保存。

我试过使用console.log() 检查输出,结果为“有效”。所以我真的不知道哪里出了错。

目前,我正在使用XAMPP进行本地测试。

我使用的代码

The Javascript:

(function($){

  // Validate Captcha
  $.fn.validateCaptcha = function() {

    challengeField = $(\'input#recaptcha_challenge_field\').val();
    responseField = $(\'input#recaptcha_response_field\').val();

    $.ajax({
        type: \'POST\',
        url: the_ajax_script.ajaxurl,
        data: \'action=validate_captcha&recaptcha_challenge_field=\' + challengeField + \'&recaptcha_response_field=\' + responseField,
        async: false,

        success:function(result)
          {
            //console.log( result );

            if(result != \'Valid\') {

              $(\'#captchaError\').html(\'<p class="error">The security code you entered did not match. Please try again.</p>\');
              $captchaFlag = \'Invalid\';
              Recaptcha.reload();

            } else {

              $(\'#memberInformation span\').css({\'color\':\'green\'});
              $(\'#memberInformation span\').html(html.message).show(3000);
              $(\'#captchaError\').html(\'<p>Success!</p>\');
              $captchaFlag = \'Valid\';
              dataString = form.serializeArray();
              getSearchMembers(dataString);

            }
          }
      }).responseText;
  }

    $(\'#registerform\').submit(function() {
      var form = $(this);

      if (form.validationEngine(\'validate\')) {
        $(\'#memberInformation span\').html(\'\');
        form.validateCaptcha();
      } else {
        $(\'#memberInformation span\').css(\'color\',\'#ff0000\').html(\'Please fill out required fields\').show(3000);
      }
      return false;
    });

})(jQuery);

The PHP:

function validate_Captha() {
  $privatekey = "xxxxxxxxxx"; //<!----- private key here
  $resp = recaptcha_check_answer ($privatekey,
            $_SERVER["REMOTE_ADDR"],
            $_POST["recaptcha_challenge_field"],
            $_POST["recaptcha_response_field"]);

  if (!$resp->is_valid) {
    // Incorrect CAPTCHA input
    echo "Error\\n";
    die ("The reCAPTCHA wasn\'t entered correctly. Please go back and try it again.\\n(reCAPTCHA said: " . $resp->error . ")");
  } else {
    echo "Valid";
    die();
  }
}
add_action( \'wp_ajax_validate_captcha\', \'validate_Captha\' );
add_action( \'wp_ajax_nopriv_validate_captcha\', \'validate_Captha\' );

1 个回复
最合适的回答,由SO网友:Giraldi 整理而成

刚刚发现reCaptcha 事实上rejects CAPTCHAs which are submitted to their server more than once. 因为我用的是WP-reCAPTCHA plugin, 插件resubmitted 我提交AJAX后的验证码。所以我只是commented out 插件中用于提交的行,该行位于文件中recaptcha.php, 第27行:

$this->register_filters();

结束