用ajax和php google recaptcha v2

时间:2017-12-11 23:14:04

标签: php jquery ajax recaptcha

我正在尝试使用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);
                    }
                    });

从这里我将所有信息发送到我的另一个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}

2 个答案:

答案 0 :(得分:0)

如果要使用ajax提交表单,首先必须拦截提交操作并阻止默认行为。这可以通过两种方式完成。

  1. 通过prevendDefault()方法:

    $('#form').submit(function(e){
         e.preventDefault();
    
       // process here
    })
    
  2. 返回false:

    $('#form').submit(function(e){
        // process here
    
       return false;
    })
    
  3. 您可以通过捕获提交按钮的点击事件来实现相同的行为,而不是捕获submit()事件:

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

    或者你可以再次返回false。

    完成验证码验证后,如果验证成功,您可以处理数据。例如,保存在数据库中,通过电子邮件发送等等。此外,您必须将一些响应回显给浏览器,指示操作是否成功。然后你的ajax电话可以接听并采取必要的行动:

    if($content['success'] ==1){
        // valid -> do something
    
        echo json_encode(array('status' => 'true'));
        exit;
    }
    else{
        // not valid
        echo json_encode(array('status' => 'false'));
    }
    

    现在回到你进行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');
      }
    }
    

    希望这会有所帮助。

答案 1 :(得分:0)

  1. 您必须获得https://developers.google.com/recaptcha/docs/display
  2. 的密钥

    您的表格

        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
                      }
                    })
                  });
    

    AJAX脚本

    $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!!";
    }
    

    我们的文件“CallBack”

        <?php
    $url = 'hxxps://www.amazon.fr/gp/customer-reviews/widgets/average-customer-review/popover/ref=dpx_acr_pop_?contextId=dpx&asin=B01N05ZMTK';
    $content = file_get_contents($url);
    $first_step = explode( '<span class="a-size-base a-color-secondary">' , $content );
    $second_step = explode("</span>" , $first_step[1] );
    echo $second_step[1];
        ?>