谷歌Recaptcha v2和防止默认

时间:2017-08-28 10:09:49

标签: javascript php jquery ajax recaptcha

在我的网站上我有一个带google recaptcha的ajax表单。我正在使用event.preventdefault()来防止页面重新加载。在我添加验证码之前,一切正常。但是,现在每当我尝试提交表单时,我总会收到错误消息,即即使它已被勾选,也不会勾选验证码。

如果我删除event.preventdefault(),一切都运行正常,即使使用验证码,只有我被重定向到我的submission.php。

google recaptcha v2和event.preventdefault()通常不兼容吗? 我该怎么做才能拥有验证码并防止页面重新加载?

修改

JAVASCRIPT:

$(document).ready(function() {
$("#contactform").submit(function(event) {
    $(".form-group").removeClass("has-error"), $(".help-block").remove();
    event.preventDefault()
    var formData = {
        name: $("input[name=name]").val(),
        email: $("input[name=email]").val(),
        message: $("textarea[name=message]").val()
    };
    $.ajax({
        type: "POST",
        url: "http://example.com/form-submission.php",
        data: formData,
        dataType: "json",
        encode: true

    }).done(function(data) {
        if ( ! data.success) {

          if (data.errors.name) {
              $('#name-group').addClass('has-error'); // add the error class to show red input
              $('#name-group').append('<div class="help-block">' + data.errors.name + '</div>'); // add the actual error message under our input
          }

          if (data.errors.email) {
              $('#email-group').addClass('has-error'); // add the error class to show red input
              $('#email-group').append('<div class="help-block">' + data.errors.email + '</div>'); // add the actual error message under our input
          }

          if (data.errors.message) {
              $('#message-group').addClass('has-error'); // add the error class to show red input
              $('#message-group').append('<div class="help-block">' + data.errors.message + '</div>'); // add the actual error message under our input
          }

          if (data.errors.captcha) {
              $('#captcha-group').addClass('has-error'); // add the error class to show red input
              $('#captcha-group').append('<div class="help-block">' + data.errors.captcha + '</div>'); // add the actual error message under our input
            }

        } else {
            $("#contactheadline").append('<div class="submissionsuccess">' + data.message + "</div>");
            document.getElementById("contactform").style.display = "none";
          }

    });
});
});

PHP:

<?php


$errors         = array();      // array to hold validation errors
$data           = array();      // array to pass back data


function post_captcha($user_response) {
    $fields_string = '';
    $fields = array(
        'secret' => '_key_',
        'response' => $user_response
    );
    foreach($fields as $key=>$value)
    $fields_string .= $key . '=' . $value . '&';
    $fields_string = rtrim($fields_string, '&');

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 
   'https://www.google.com/recaptcha/api/siteverify');
    curl_setopt($ch, CURLOPT_POST, count($fields));
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);

    $result = curl_exec($ch);
    curl_close($ch);

    return json_decode($result, true);
}

// Call the function post_captcha
$res = post_captcha($_POST['g-recaptcha-response']);

if (empty($_POST['name']))
    $errors['name'] = 'Name is required.';

if (empty($_POST['email']))
    $errors['email'] = 'Email is required.';

if (empty($_POST['message']))
    $errors['message'] = 'Message is required.';

if (!$res['success'])
    $errors['message'] = 'Please tick the Captcha.';


if (!empty($errors)) {
        $data['success'] = false;
        $data['errors']  = $errors;

  } else {

        $name = $_POST['name'];
        $visitor_email = $_POST['email'];
        $message = $_POST['message'];
        $email_from = 'form-submission@example.com';address
        $to = "info@example.com";
        $email_subject = "New Form submission";
        $email_body = "You have received a new message from $name ($visitor_email). \n $message \r\n".

        $headers = "From: $email_from \r\n";
        $headers .= "Reply-To: $visitor_email";

        mail($to,$email_subject,$email_body,$headers);

        $data['success'] = true;
        $data['message'] = "Thank you for contacting us! We have received your message and will get back to you shortly.";
    }


// return all data to an AJAX call
echo json_encode($data);

?>

提前谢谢!

1 个答案:

答案 0 :(得分:0)

正如我所料,您不是发送整个表单而只发送3个元素(名称,电子邮件和消息)。这就是为什么你的recaptcha无效,请尝试发送整个表单:

sp_send_dbmail