带有reCaptcha的PHP Ajax表单未提交 [英] PHP Ajax form with reCaptcha not submitting

查看:88
本文介绍了带有reCaptcha的PHP Ajax表单未提交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的表格具有ajax和reCaptcha验证.我在使reCaptcha正常工作时遇到了一些麻烦.我不断从sendmail.php收到错误消息"Please click the reCAPTCHA box"(错误400). 我在这里想念什么?

I have form with ajax and reCaptcha validation. I have some trouble making the reCaptcha work. I keep getting the error message "Please click the reCAPTCHA box" from sendmail.php (error 400). What am I missing here?

HTML:

<div class="modal-body">
  <div class="statusMsg"></div>
  <form id="contactform" action="sendmail.php" method="post">
    <div class="form-group">
      <label for="inputName">Name</label>
      <input type="text" class="form-control" id="inputName" placeholder="Enter your name" />
    </div>
    <div class="form-group">
      <label for="inputPhone">Phone</label>
      <input type="phone" class="form-control" id="inputPhone" placeholder="Enter your phone no." />
    </div>
    <div class="form-group">
      <label for="inputEmail">Email</label>
      <input type="email" class="form-control" id="inputEmail" placeholder="Enter your email" />
    </div>
    <div class="form-group">
      <label for="inputMessage">Message</label>
      <textarea name="comment" class="form-control" id="inputMessage" placeholder="Enter your message"></textarea>
    </div>
    <div class="messages"></div>
  </form>
</div>

<div class="modal-footer">
  <div class="captcha-box">
    <div class="g-recaptcha" data-theme="dark" data-sitekey="6LdqpBIUAAAAAAq17acWDx1oHuJsrQOdVQFb88rh"> </div>
  </div>
  <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
  <button type="submit" class="btn btn-primary" id="buttonid">SUBMIT</button>
</div>

js:

<script>
  $(function() {
    // Get the form.
    var form = $('#contactform');

    // Get the messages div.
    var formMessages = $('.messages');

    // Set up an event listener for the contact form.
    $('#buttonid').click(function(e) {
      // Stop the browser from submitting the form.
      e.preventDefault();

      // Serialize the form data.
      var formData = $(form).serialize();

      // Submit the form using AJAX.
      $.ajax({
          type: 'POST',
          url: $(form).attr('action'),
          data: formData
        })
        .done(function(response) {
          // Make sure that the formMessages div has the 'success' class.
          $(formMessages).removeClass('error');
          $(formMessages).addClass('success');

          // Set the message text.
          $(formMessages).text(response);

          // Clear the form.
          $('#inputName').val('');
          $('#inputMail').val('');
          $('#inputMessage').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.');
          }
        });
    });
  });
</script>

sendmail.php:

sendmail.php:

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

    // If the Google Recaptcha box was clicked
    if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
        $captcha=$_POST['g-recaptcha-response'];
        $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=MYKEY&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);
          $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
          $message = trim($_POST["message"]);
          if ( empty($name) 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;
          }
          $recipient = "will@additlater.com";
          $subject = "New message from $name";
          $email_content = "Name: $name\n";
          $email_content .= "Email: $email\n\n";
          $email_content .= "Message:\n$message\n";
          $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. Check your email address.";
          }

      }

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

  }

  // If the Google Recaptcha box was not clicked
  else {
    http_response_code(400);
    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.";
}
?>

推荐答案

我解决了.似乎有几处错误.

I solved it. it seems there was a couple of things wrong.

  1. 正如KyleS所述,reCapthca框必须位于<form>内.
  2. 表单输入字段必须具有name=""才能使.serialize()工作.
  1. As KyleS mentioned, the reCapthca box need to be inside the <form>.
  2. Form input fields need to have a name="" in order for .serialize() to work.

之后,代码现在可以按预期工作了.

After that, the code now works as intended.

这篇关于带有reCaptcha的PHP Ajax表单未提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆