Javascript 带有 AJAX 的 ReCaptcha 2.0

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30006081/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:28:17  来源:igfitidea点击:

ReCaptcha 2.0 With AJAX

javascriptphpjqueryajaxrecaptcha

提问by Gofilord

I have managed to get ReCaptcha 2.0 working in my website. However, it's only working when I don't use AJAX and I let the form submit "naturally".

我已经设法让 ReCaptcha 2.0 在我的网站上工作。但是,它仅在我不使用 AJAX 并且让表单“自然”提交时才有效。

I want to submit the form with the captcha and alert the user with a success note without refreshing the page.

我想提交带有验证码的表单,并在不刷新页面的情况下用成功提示提醒用户。

I tried the following code, but it seems like the server doesn't get the user response:

我尝试了以下代码,但似乎服务器没有收到用户响应:

HTML:

HTML:

<form class="form" action="javascript:void(0)" novalidate>
    <!-- all the inputs... -->

    <!-- captcha -->
    <div class="input-group">
        <div class="g-recaptcha" data-sitekey="6LdOPgYTAAAAAE3ltWQGar80KUavaR-JblgPZjDI"></div>
    </div>

    <div class="errors" id="errors" style="display: none"></div>

    <div class="input-group">
        <input type="button" value="Send" class="btn-default right" id="submit">
        <div class="clear"></div>
    </div>
</form>

JS:

JS:

$('#submit').click(function(e) {
    console.log('clicked submit'); // --> works

    var $errors = $('#errors'),
        $status = $('#status'),

        name = $('#name').val().replace(/<|>/g, ""), // prevent xss
        email = $('#email').val().replace(/<|>/g, ""),
        msg = $('#message').val().replace(/<|>/g, "");

    if (name == '' || email == '' || msg == '') {
        valid = false;
        errors = "All fields are required.";
    }

    // pretty sure the problem is here
    console.log('captcha response: ' + grecaptcha.getResponse()); // --> captcha response: 

    if (!errors) {
        // hide the errors
        $errors.slideUp();
        // ajax to the php file to send the mail
        $.ajax({
            type: "POST",
            url: "http://orenurbach.com/assets/sendmail.php",
            data: "email=" + email + "&name=" + name + "&msg=" + msg + "&g-recaptcha-response=" + grecaptcha.getResponse()
        }).done(function(status) {
            if (status == "ok") {
                // slide down the "ok" message to the user
                $status.text('Thanks! Your message has been sent, and I will contact you soon.');
                $status.slideDown();
                // clear the form fields
                $('#name').val('');
                $('#email').val('');
                $('#message').val('');
            }
        });
    } else {
        $errors.text(errors);
        $errors.slideDown();
    }
});

PHP:

PHP:

<?php
    // assemble the message from the POST fields

    // getting the captcha
    $captcha = '';
    if (isset($_POST['g-recaptcha-response']))
        $captcha = $_POST['g-recaptcha-response'];
    echo 'captcha: '.$captcha;

    if (!$captcha)
        echo 'The captcha has not been checked.';
    // handling the captcha and checking if it's ok
    $secret = 'MY_SECRET';
    $response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']), true);

    var_dump($response);

    // if the captcha is cleared with google, send the mail and echo ok.
    if ($response['success'] != false) {
        // send the actual mail
        @mail($email_to, $subject, $finalMsg);

        // the echo goes back to the ajax, so the user can know if everything is ok
        echo 'ok';
    } else {
        echo 'not ok';
    }
?>

The resultin the PHP page:

PHP页面中的结果

captcha: The captcha has not been checked.array(2) { ["success"]=> bool(false) ["error-codes"]=> array(1) { [0]=> string(22) "missing-input-response" } } not ok

Bottom lineis, how can I get the input response manually without it automatically going with the rest of the POST data?

最重要的是,如何手动获取输入响应而不自动处理其余的 POST 数据?

采纳答案by Gofilord

Ok, this was pretty silly.

好吧,这太愚蠢了。

I have done a couple of things wrong:

我做错了几件事:

  • In the PHP file, all the strings had single quotes on them, and that caused problems.
  • Throughout the testing, I added multiple printings of things in the PHP file, thus the if (status == "ok")was never working. I did get the emails but did not get any conformation that I did and now I see why.
  • When I wanted to check what the PHP file was omitting, I simply went to it's address in the URL and always got an error. Even when the mails were sent. Now I understand that that is not the correct way of checking the logs.
  • 在 PHP 文件中,所有字符串都带有单引号,这会导致问题。
  • 在整个测试过程中,我在 PHP 文件中添加了多次打印内容,因此if (status == "ok")无法正常工作。我确实收到了电子邮件,但没有得到我所做的任何确认,现在我明白了原因。
  • 当我想检查 PHP 文件遗漏了什么时,我只是在 URL 中访问它的地址,但总是出现错误。甚至当邮件被发送。现在我明白这不是检查日志的正确方法。

Thanks to @Samurai who helped my figure out things.

感谢@Samurai 帮助我解决了问题。



Final PHP code:

最终的 PHP 代码:

<?php
    // assemble the message from the POST fields

    // getting the captcha
    $captcha = "";
    if (isset($_POST["g-recaptcha-response"]))
        $captcha = $_POST["g-recaptcha-response"];

    if (!$captcha)
        echo "not ok";
    // handling the captcha and checking if it's ok
    $secret = "MY_SECRET";
    $response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$captcha."&remoteip=".$_SERVER["REMOTE_ADDR"]), true);

    // if the captcha is cleared with google, send the mail and echo ok.
    if ($response["success"] != false) {
        // send the actual mail
        @mail($email_to, $subject, $finalMsg);

        // the echo goes back to the ajax, so the user can know if everything is ok
        echo "ok";
    } else {
        echo "not ok";
    }
?>