简体   繁体   English

使用ajax和php的google recaptcha v2

[英]google recaptcha v2 with ajax and php

I am trying to validate google recaptcha v2 using ajax php but it submitted without validating my code. 我正在尝试使用Ajax php验证Google Recaptcha v2,但提交时未验证我的代码。

if((fnameerr == "no") && (lnameerr == "no") && (emailerr == "no") && (cnameerr == "no") && (discounterr == "no") && (addresserr == "no") && (descerr == "no")){
                $.ajax({
                    url:"promoform.php",
                    method:"POST",
                    data:{fname:fname, lname:lname, email:email, cname:cname, discount:discount, address:address, desc:desc, website:website, captcha: grecaptcha.getResponse()},
                    success: function(data){
                        if($("#promotionSuccess").hasClass("hidden")){
                            $("#promotionSuccess").removeClass("hidden");
                        }
                        $("#mailErrorMessage").html(data);
                    }
                    });

from here I'm sending all info to my another php page and I am validating recaptcha there: 从这里,我将所有信息发送到我的另一个php页面,并在那里验证recaptcha:

$secret = "my secret key is here which I got from google";
$response = $_POST["captcha"];
$remoteip = $_SERVER['REMOTE_ADDR'];
$url = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$secret&response=$response&remoteip=$remoteip");
$content = json_decode($url, TRUE);
if($content['success'] ==1){ do somthing}

If you are to submit the form with ajax, first you have to intercept the submit action and block the default behavior. 如果要使用ajax提交表单,则首先必须拦截Submit操作并阻止默认行为。 This can be done in two ways. 这可以通过两种方式完成。

  1. via prevendDefault() method: 通过prevendDefault()方法:

    \n$('#form').submit(function(e){ $('#form')。submit(function(e){\n     e.preventDefault(); e.preventDefault();\n\n   // process here //在这里处理\n}) })\n
  2. by returning false: 通过返回false:

    \n$('#form').submit(function(e){ $('#form')。submit(function(e){\n    // process here //在这里处理\n\n   return false; 返回false;\n}) })\n

Instead of capturing the submit() event, you can also achieve the same behavior by capturing the submit button's click event: 除了捕获Submit()事件,您还可以通过捕获Submit按钮的click事件来实现相同的行为:

$('#mysubmitbutton').click(function(e){
   e.preventDefault();
   // process here
})

or again you can return false. 还是可以再次返回false。

When your captcha validation is done, if it is successful you can process your data. 验证码验证完成后,如果验证成功,则可以处理数据。 for example save in a db, emailing etc. Also you have to echo some response back to the browser indicating whether the operation was successful or not. 例如,保存在数据库中,通过电子邮件发送等。此外,您还必须向浏览器回显一些响应,以指示操作是否成功。 Then your ajax call can pick it up and take the necessary action: 然后,您的ajax调用可以接听并采取必要的措施:

if($content['success'] ==1){
    // valid -> do something

    echo json_encode(array('status' => 'true'));
    exit;
}
else{
    // not valid
    echo json_encode(array('status' => 'false'));
}

Now back in where you made your ajax call, you can process the response as follows: 现在回到您的ajax调用位置,可以按以下方式处理响应:

success: function(data){
  res = JSON.parse(data);    // parse response to a js object

  if(res.status == 'true')
  {
     alert('Form was submitted successfully!');
  }
  else
  {
     alert('Captcha validation falied! Please try again');
  }
}

Hope this helps. 希望这可以帮助。

  1. Your must get key on https://developers.google.com/recaptcha/docs/display 您必须在https://developers.google.com/recaptcha/docs/display上获得密钥

Your form 您的表格

<form id="order-form">
    <input  id="Name" type="text" placeholder="Name" name="name" required/>
    <input id="email" type="email" placeholder="Email" required/>
    <textarea id="message" name="message" required cols="50" rows="5" maxlength="1000"></textarea>

    <div class="g-recaptcha" data-sitekey="YOUR KEY"></div>
    <button type="submit">Send</button>
</form>

AJAX script AJAX脚本

    var contactForm = $("#order-form");
              contactForm.on("submit", function(e) {
                e.preventDefault();
                var name = $("#name").val();
                var email = $("#email").val();
                var message = $("#message").val();

                $.ajax({
                  type: "POST",
                  url: "callback.php", //Our file 
                  data: {
                    name: name,
                    email: email,
                    message: message,                    
                    captcha: grecaptcha.getResponse()

                  },
                  success: function(response) {
                   //Here add to front-end message
                    $('#order-form +.result-form').html(response);
                    grecaptcha.reset(); // Reset reCaptcha
                  }
                })
              });

OUR file "CallBack" 我们的文件“ CallBack”

$username = $_POST['name'];
$usermail = $_POST['email'];
$usermessage = $_POST['message'];

$secret=" OUR SECRET KEY FROM reCaptcha"; 
$response=$_POST["captcha"];
$verify=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret={$secret}&response={$response}");
$captcha_success=json_decode($verify);
if ($captcha_success->success==false) {
echo "Error, you are a robot?";
}
else if ($captcha_success->success==true) {
echo "successful!!";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM