简体   繁体   中英

Validate reCAPTCHA in bootstrap modal using ajax

We have a reCAPTCHA witch loads on bootstrap modal opening at HERE . There is not any form to submit. I just want to validate reCAPTCHA when user checked the reCAPTCHA using ajax request. In other words, how to recognize (using javascript) when user checked the reCAPTCHA and after it validate reCAPTCHA from server side (for example validate.php) using an ajax request? I tried using grecaptcha.getResponse(); but not useful. Below is my code:

    <html>
  <head>
    <title>Test</title>
    <script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap-theme.min.css" rel="stylesheet">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
  </head>
  <body>
      <button id="showModal" type="button">Show Modal</button>

<div class="modal fade" id="myModal">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title">Modal title</h4>
      </div>
      <div class="modal-body">
        <div id="captcha"></div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>
      <script>
"use strict";

$("#showModal").click(function() {
    $("#myModal").modal("show");
    setTimeout(function() {
        createRecaptcha();
    }, 100);
});

function createRecaptcha() {
    grecaptcha.render("captcha", {sitekey: "YOUR_PUBLIC_KEY", theme: "light"});
}
      </script>
      <script src="https://www.google.com/recaptcha/api.js?onload=loadCaptcha&render=explicit"></script>
  </body>
</html>

It's simple as it gets: get reCaptcha response using it's callback function, send it with ajax to your PHP controller. Here's the code:

var captchaResponse = "";
var recaptchaWidgId = null; // (optional) used for resetting reCaptcha on showing modal.
// It's useful since reCaptcha has a time limit.

$("#showModal").click(function() {
    $("#myModal").modal("show");
    if (recaptchaWidgId != null) // if modal is already shown this load
        grecaptcha.reset(recaptchaWidgId);
    else {
        setTimeout(function() {
            createRecaptcha();
        }, 100);
    }
});

function createRecaptcha() {
    recaptchaWidgId = grecaptcha.render("captcha", {
    sitekey: "YOUR_PUBLIC_KEY", theme: "light", 
    'callback': recaptchaCallback}); // callback will be declared
}

recaptchaCallback = function () { // initializing callback function
    captchaResponse = grecaptcha.getResponse();

    $.post('YOUR_CONTROLLER_URL', {
    "recaptchaResponse": captchaResponse
    }) // optionally, you can add event handlers and manipulate DOM on "done", "fail" and
    // etc. You can further control it by throwing concrete Http status codes with PHP
    //and using "if" or "switch" in handlers just like this:
        .done(function (data) { // data is a jqXHR object, result of post
            if (data.status)
            {
                if (data.status != 200)
                {
                    // your code, such as:
                    var message = JSON.parse(data.responseText);
                }
            }
        }
};

PHP code:

uses Recaptcha php library from google https://github.com/google/recaptcha

public function YOUR_CONTROLLER_METHOD()
{
$captchaResponse = $this->input->post('recaptchaResponse'); // I'm using CodeIgniter

if (isset($captchaResponse)) {
    // Google's PHP plugin is used for this verification. It's on their site.
    $recaptcha = new ReCaptcha('YOUR_SECRET_KEY', new \ReCaptcha\RequestMethod\CurlPost());
    $resp = $recaptcha->verify($captchaResponse, 'YOUR_IP_ADDRESS');
    if (!$resp->isSuccess()) {
        http_response_code(400); // for example, most cases this HTTP CODE is used
        echo json_encode(['status' => 'error', 'message' => '...']);         // you can echo your 
        //messages to JQuery event handlers
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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