A
A
AbsolvoTe2018-02-19 20:15:51
JavaScript
AbsolvoTe, 2018-02-19 20:15:51

How to validate multiple recaptchas for ajax forms?

Hello!
Connect API:

<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>

I create a function:
var callbackCaptcha;
var questionCaptcha;

function onloadCallback() {
  callbackCaptcha = grecaptcha.render('callback_captcha', {
    'sitekey' : 'ключ'
  });

  questionCaptcha = grecaptcha.render('question_captcha', {
    'sitekey' : 'ключ'
  });
}

I output:
<form>
  <div id="callback_captcha"></div>
  <p class="test-danger"></p>
</form>
<form>
  <div id="question_captcha"></div>
  <p class="test-danger"></p>
</form>

Submit ajax form:
$("form").submit(function() { //Change
    var th = $(this);
    var captcha = grecaptcha.getResponse();
    if (!captcha.length) {
      $('.test-danger').text('*Вы не прошли проверку "Я не робот"');
    } else {
      $.ajax({
        type: "POST",
      url: uri+"/mail.php", //Change
      data: th.serialize()
    }).done(function() {
      th.find(".success").addClass("active");
      setTimeout(function() {
        // Done Functions
        th.find(".success").removeClass("active");
        th.trigger("reset");
        $.magnificPopup.close();
        $('.test-danger').text('');
      }, 3000);
    });
  }
  return false;
});

Only the first callback_captcha form is sent to the result. Tell me, please, what am I doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
grinat, 2018-02-19
@AbsolvoTe

According to the docs:
var onloadCallback = function() {
// Renders the HTML element with id 'example1' as a reCAPTCHA widget.
// The id of the reCAPTCHA widget is assigned to 'widgetId1'.
widgetId1 = grecaptcha.render('example1', {
'sitekey' : 'your_site_key',
'theme' : 'light'
});
Therefore, it should work like this:
grecaptcha.getResponse(callbackCaptcha)
grecaptcha.getResponse(questionCaptcha)
I still don’t think it will work, validation is asynchronous in theory. So either
var verifyCallback = function(response) {
if(response){
$("form").
... and further this hell on juqery
}
};
callbackCaptcha = grecaptcha.render('callback_captcha', {
'sitekey' : 'key',
'callback': verifyCallback
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question