javascript - 使用 AJAX 时 ReCAPTCHA 不起作用

标签 javascript php jquery html ajax

我从我的联系表单中收到了垃圾邮件,因此我将 googles ReCAPTCHA 添加到了我的联系表单中。经过多次尝试和失败后,我正在寻求帮助。

首先,我的 HTML 处于显示状态并调用 ajaxsubmit.php

            <div class="reveal" id="contactModal" data-reveal>
          <h1>Contact Us</h1>
          <div class="grid-x grid-margin-x">
            <form id="ajax-contact" method="post" action="/assets/js/ajaxsubmit.php" class="large-12 cell">
              <div class="grid-x grid-margin-x">
                <div class="large-6 cell">
                  <label>Name*</label>
                  <input id="name" name="name" required type="text" placeholder="Name..." /> </div>
                <div class="large-6 cell">
                  <label>Company*</label>
                  <input id="company" type="text" placeholder="Company..." name="company" required/> </div>
              </div>
              <div class="grid-x grid-margin-x">
                <div class="large-6 cell">
                  <label>Email*</label>
                  <input id="email" type="email" placeholder="Email..." name="email" required /> </div>
                <div class="large-6 cell">
                  <label>Phone*</label>
                  <input id="phone" type="tel" placeholder="Phone..." name="phone" required/> </div>
              </div>
              <div class="grid-x grid-margin-x">
                <div class="large-12 cell">
                  <label>Message*</label>
                  <textarea id="message" placeholder="Message..." name="message" required></textarea>
                </div>
              </div>
              <div class="grid-x grid-margin-x">
                  <div class="large-6 cell">
                  <div class="g-recaptcha" data-sitekey="MYSITEKEY"></div>
                  </div>
                <div class="large-6 clear-fix">
                  <button class="button float-right" type="submit">Submit</button>
                </div>
              </div>
            </form>
            <div id="form-messages"></div>
          </div>
          <button class="close-button" data-close aria-label="Close reveal" type="button"> <span aria-hidden="true">&times;</span> </button>
        </div>

用户完成表单并重新验证后,我的 ajax.js 文件会在用户单击“提交”时抓取它并阻止默认操作。

$(function() {
var form = $("#ajax-contact");
var formMessages = $("#form-messages");
//We set our own custom submit function
$(form).submit(function(event) {
//Prevent the default behavior of a form
event.preventDefault();
//Get the values from the form
var name = $("#name").val();
var company = $("#company").val();
var phone = $("#phone").val();
var email = $("#email").val();
var message = $("#message").val();
//AJAX POST
$.ajax({
type: "POST",
url: "/assets/js/ajaxsubmit.php",
data: {
name: name,
company: company,
email: email,
phone: phone,
message: message,
captcha: grecaptcha.getResponse()}
}).done(function(response) {
$(formMessages).removeClass("error");
$(formMessages).addClass("success");
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$("#name").val("");
$("#company").val("");
$("#phone").val("");
$("#email").val("");
$("#message").val("");
}).fail(function(data) {
// Make sure that the formMessages div has the "error" class.
$(formMessages).removeClass("success");
$(formMessages).addClass("error");
// Set the message text.
if (data.responseText !== "") {
    $(formMessages).text(data.responseText);
} else {
    $(formMessages).text("Oops! An error occured and your message could not be sent.");
}
});
});
});

在 Ajax.js 之后,它通过 Ajax jquery 函数 $.ajax 发布到我的 ajaxsubmit.php 文件。

 <?php
// If the form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {

// If the Google Recaptcha box was clicked
if(isset($_POST[‘captcha’]) && !empty($_POST[‘captcha’])){    
$captcha=$_POST[‘captcha’];
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=MYSECRET&response=".$captcha."&remoteip=".$_SERVER[‘REMOTE_ADDR’]);
$obj = json_decode($response);

// If the Google Recaptcha check was successful
if($obj->success == true) {
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$company = strip_tags(trim($_POST["company"]));
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$phone = strip_tags(trim($_POST["phone"]));
$message = trim($_POST["message"]);
// Check that data was sent to the mailer.
        if ( empty($name) OR empty($company) OR empty($phone) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
        // Set the recipient email address.
        $recipient = "EMAIL";

        // Set the email subject.
        $subject = "New contact from $name";

        // Build the email content.
        $email_content = "Name: $name\n";
        $email_content .= "Email: $email\n\n";
        $email_content .= "Company: $company\n\n";
        $email_content .= "Phone: $phone\n\n";
        $email_content .= "Message:\n$message\n";

        // Build the email headers.
        $email_headers = "From: $name <$email>";
if (mail($recipient, $subject, $email_content, $email_headers)) {
http_response_code(200);
echo "Thank You! Your message has been sent.";
}

else {
http_response_code(500);
echo "Oops! Something went wrong, and we couldn’t send your message.";
}

}

// If the Google Recaptcha check was not successful
else {
echo "Robot verification failed. Please try again.";
}

}

// If the Google Recaptcha box was not clicked
else {
echo "Please click the reCAPTCHA box.";
}

}

// If the form was not submitted
// Not a POST request, set a 403 (forbidden) response code.
else {
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>

现在这就是我的问题所在,它永远不会超过第一个 if 语句 if(isset($_POST['captcha']) && !empty($_POST['captcha'])) 并直接转到请单击 ReCAPTCHA 框。如果我回显验证码变量,它里面就有数据。所以我不明白为什么它不会继续到第一个 if 语句,非常感谢任何帮助。谢谢!!!

最佳答案

我认为问题是 $_POST['captcha']

来自 Google 开发网站

g-recaptcha-response POST parameter when the user submits the form on your site
grecaptcha.getResponse(opt_widget_id) after the user completes the reCAPTCHA challenge
As a string argument to your callback function if data-callback is specified in either 
the g-recaptcha tag attribute or the callback parameter in the grecaptcha.render method

在 recaptcha 网站上,您可以找到有关如何验证 recaptcha 本身的详细信息: https://www.google.com/recaptcha/admin#site/319444416

关于javascript - 使用 AJAX 时 ReCAPTCHA 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50105955/

相关文章:

javascript - 带有逻辑或的奇怪 JavaScript 赋值

php - 如何声明全局变量并初始化

javascript - 在 jQuery 中访问 PHP $_SESSION 变量并执行错误处理和页面重定向

javascript - 未捕获的 TypeError : Failed to construct 'File' : Please use the 'new' operator, 此 DOM 对象构造函数不能作为函数调用

javascript - 将部分 View 注入(inject) div 标签

javascript - 如何在 Electron 应用程序中获取持久权限?

javascript - 引用错误: regeneratorRuntime is not defined (but working inside a scope)

php - 违反完整性约束 : 1062 Duplicate field

javascript - Twitter-Bootstrap Scrollspy

javascript - 可选的 RegExp 标识在 ES6 中不起作用