添加&使用PHP + Ajax表单验证reCAPTCHA

时间:2018-02-08 11:34:06

标签: php ajax recaptcha

解决了问题!

Juste替换:



<div class='form-group'>
    <div id="google" class="g-recaptcha" data-sitekey="MYPUBLICKEY" data-callback="callback" required data-error="Validate recaptcha"></div>
    <div class="help-block with-errors"></div>
</div>
&#13;
&#13;
&#13;

有了这个:

&#13;
&#13;
                            <div id="recaptcha" class="g-recaptcha" data-sitekey="MYPUBLICKEY"></div>
                            <div class="help-block with-errors">
                                <span class="msg-error error"></span>
                            </div>
&#13;
&#13;
&#13;

将此js脚本添加到新文件中:

&#13;
&#13;
$( '#submit' ).click(function(){
  var $captcha = $( '#recaptcha' ),
      response = grecaptcha.getResponse();
  
  if (response.length === 0) {
    $( '.msg-error').text( "reCAPTCHA is mandatory" );
    if( !$captcha.hasClass( "error" ) ){
      $captcha.addClass( "error" );
    }
  } else {
    $( '.msg-error' ).text('');
    $captcha.removeClass( "error" );
    alert( 'reCAPTCHA marked' );
  }
})
&#13;
&#13;
&#13;

我想在我的小型联系人中添加一个reCaptcha V2。 这个表格使用PHP&amp;用于检查所有字段是否为空的Ajax。 如果缺少某个字段,则会在此字段下方显示一条消息,通知用户。 当所有字段都完成后,ajax会发送电子邮件,而不会重新加载页面。

我想用reCAPTCHA做同样的事情。我已经阅读了官方谷歌文档,但对我来说有点困难。如果我理解正确,我必须使用我的私钥来检查g-recaptcha-response。如果用户不像其他字段那样完成reCaptcha,我不知道如何操纵令牌来显示消息。

在线示例: http://sosmooth.fr/form5/

rar文件夹中的所有文件: http://sosmooth.fr/form5.rar

Js档案:

&#13;
&#13;
$("#contactForm").validator().on("submit", function(event) {
  if (event.isDefaultPrevented()) {
    // handle the invalid form...
    formError();
    submitMSG(false, "Did you fill in the form properly ?");
  } else {
    // everything looks good!
    event.preventDefault();
    submitForm();
  }
});

function submitForm() {
  // Initiate Variables With Form Content
  var name = $("#name").val();
  var email = $("#email").val();
  var msg_subject = $("#msg_subject").val();
  var message = $("#message").val();


  $.ajax({
    type: "POST",
    url: "assets/php/form-process.php",
    data: "name=" + name + "&email=" + email + "&msg_subject=" + msg_subject + "&message=" + message,
    success: function(text) {
      if (text == "success") {
        formSuccess();
      } else {
        formError();
        submitMSG(false, text);
      }
    }
  });
}

function formSuccess() {
  $("#contactForm")[0].reset();
  submitMSG(true, "Message Submitted!")
}

function formError() {
  $("#contactForm").removeClass().addClass('shake animated').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
    $(this).removeClass();
  });
}

function submitMSG(valid, msg) {
  if (valid) {
    var msgClasses = "h3 text-center tada animated text-success";
  } else {
    var msgClasses = "h3 text-center text-danger";
  }
  $("#msgSubmit").removeClass().addClass(msgClasses).text(msg);
}
&#13;
&#13;
&#13; HTML文件:

<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <link rel="stylesheet" type="text/css" href="assets/css/animate.css" media="screen">
</head>

<body>
  <section id="content">
    <div class="container">
      <div class="row">
        <div class="col-md-9">
          <h2>Contact Form</h2>
          <!-- Start Contact Form -->
          <form role="form" id="contactForm" class="contact-form" data-toggle="validator" class="shake">
            <div class="form-group">
              <div class="controls">
                <input type="text" id="name" class="form-control" placeholder="Name" required data-error="Please enter your name">
                <div class="help-block with-errors"></div>
              </div>
            </div>
            <div class="form-group">
              <div class="controls">
                <input type="email" class="email form-control" id="email" placeholder="Email" required data-error="Please enter your email">
                <div class="help-block with-errors"></div>
              </div>
            </div>
            <div class="form-group">
              <div class="controls">
                <input type="text" id="msg_subject" class="form-control" placeholder="Subject" required data-error="Please enter your message subject">
                <div class="help-block with-errors"></div>
              </div>
            </div>
            <div class="form-group">
              <div class="controls">
                <textarea id="message" rows="7" placeholder="Massage" class="form-control" required data-error="Write your message"></textarea>
                <div class="help-block with-errors"></div>
              </div>
            </div>
            <div class='form-group'>
              <div id="google" class="g-recaptcha" data-sitekey="MYPUBLICKEY" data-callback="callback" required data-error="Validate recaptcha"></div>
              <div class="help-block with-errors"></div>
            </div>
            <button type="submit" id="submit" class="btn btn-success"></i> Send Message</button>
            <div id="msgSubmit" class="h3 text-center hidden"></div>
            <div class="clearfix"></div>
          </form>
        </div>
      </div>
    </div>
  </section>
  <!-- Main JS  -->
  <script type="text/javascript" src="assets/js/jquery-min.js"></script>
  <script type="text/javascript" src="assets/js/form-validator.min.js"></script>
  <script type="text/javascript" src="assets/js/contact-form-script.js"></script>
  <script src='https://www.google.com/recaptcha/api.js'></script>
</body>

</html>

PHP文件:

&#13;
&#13;
<?php

$privatekey = "MYPRIVATEKEY"
$errorMSG = "";

// NAME
if (empty($_POST["name"])) {
    $errorMSG = "Name is required";
} else {
    $name = $_POST["name"];
}

// EMAIL
if (empty($_POST["email"])) {
    $errorMSG .= "Email is required";
} else {
    $email = $_POST["email"];
}

// MSG SUBJECT
if (empty($_POST["msg_subject"])) {
    $errorMSG .= "Subject is required";
} else {
    $msg_subject = $_POST["msg_subject"];
}

// MESSAGE
if (empty($_POST["message"])) {
    $errorMSG .= "Message is required";
} else {
    $message = $_POST["message"];
}

$EmailTo = "john@doe.com";
$Subject = "New Message Received";

// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body.= nl2br(stripslashes($name));
$Body .= "\n";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n";
$Body .= "Subject: ";
$Body .= nl2br(utf8_decode(stripslashes($msg_subject))); 
$Body .= "\n";
$Body .= "Message: ";
$Body .= nl2br(utf8_decode(stripslashes($message))); 
$Body .= "\n";

// send email
$success = mail($EmailTo, $Subject, $Body, "From:".$email);

// redirect to success page
if ($success && $errorMSG == ""){
   echo "success";
}else{
    if($errorMSG == ""){
        echo "Something went wrong :(";
    } else {
        echo $errorMSG;
    }
}

?>
&#13;
&#13;
&#13;

0 个答案:

没有答案