Рекапча 2.0 С AJAX


Мне удалось заставить reCAPTCHA 2.0 работать на моем веб-сайте. Однако это работает только тогда, когда я не использую AJAX и позволяю форме отправляться "естественным образом".

Я хочу отправить форму с капчей и предупредить пользователя об успешном завершении , не обновляя страницу .

Я попробовал следующий код, но похоже, что сервер не получает ответа пользователя:

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:

$('#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
    // 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';
    }
?>

Результат на странице 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

Суть заключается в том, как я могу получить входной ответ вручную, не используя его автоматически вместе с остальными данными POST?

Author: Gofilord, 2015-05-02

2 answers

Ладно, это было довольно глупо.

Я сделал пару вещей неправильно:

  • В файле PHP все строки были заключены в одинарные кавычки, и это вызвало проблемы.
  • На протяжении всего тестирования я добавлял несколько печатей вещей в файл PHP, поэтому if (status == "ok") никогда не работал. Я действительно получал электронные письма, но не получил никакого подтверждения, что я сделал, и теперь я понимаю, почему.
  • Когда я хотел проверить, что пропущено в файле PHP, я просто зашел по его адресу в URL-адрес и всегда получал ошибку. Даже когда письма были отправлены. Теперь я понимаю, что это неправильный способ проверки журналов.

Спасибо @Samurai, который помог мне разобраться во всем.


Окончательный 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";
    }
?>
 24
Author: Gofilord, 2015-06-01 19:11:57

Вы хотели, чтобы в вашем javascript были эти знаки доллара? Если да, то почему?

var $errors = $('#errors'),
$status = $('#status'),
 -2
Author: TheRobMusic, 2018-02-20 14:01:48