Energizem
Energizem

Reputation: 221

Google reCAPTCHA reset multiple captchas rendered by function call

I have many reCAPTCHA's who are rendered dynamically, sometimes there are 2 sometimes 50 depends on page. I've done rendering with this:

<script src="https://www.google.com/recaptcha/api.js?onload=CaptchaCallback&render=explicit" async defer></script>
var CaptchaCallback = function(){
    $('.g-recaptcha').each(function(index, el) {
        grecaptcha.render(el, {'sitekey' : 'myKey'});
    });
};

And placed this where I want captcha to be displayed:

<div class="g-recaptcha" data-sitekey="myKey"></div>

I've got ajax call, that submits form data to process.php, and if form data isn't verified returns custom errors

$.ajax({
    type        : 'POST', 
    url         : 'process.php', 
    data        : $(this).serialize(), 
    dataType    : 'json'
})
    .done(function(data) { 
        if ( ! data.success) {    ...

It works as intended, but now I want to show message to user as part of validation, if he forgot to solve captcha.

With

var response = grecaptcha.getResponse();
if(response.length == 0){
    $('.result').append('Captcha incorrect, please click I am not robot');
}

and to reset captcha add this bellow

if ( ! data.success) {
      grecaptcha.reset();

What does it do is: reset captcha if user didn't completed all forms valid.

This all works only on 1st occurrence of reCAPTCHA. And I need it to somehow tell it to reset only captcha that is currently in use.

My best guess was to try with

var form = $(this); //get current form
 grecaptcha.reset(form);

It won't work, since i need widget ID, and not form. Can you assist me pls?

Upvotes: 2

Views: 4943

Answers (1)

Energizem
Energizem

Reputation: 221

All credits to https://stackoverflow.com/a/41860070/7327467

reset is done with

var form = $(this); //store current form

var response = grecaptcha.getResponse(jQuery(form).find('#data-widget-id').attr('data-widget-id'));
if(response.length == 0){ //append error to result div
     form.find('.result').append('<div class="alert alert-danger">' + "Captcha incorrect" + '</div>');    }

and to reset recaptcha, I've added this instead previous "grecaptcha.reset();"

grecaptcha.reset(jQuery(form).find('#data-widget-id').attr('data-widget-id'));

Hope this helps.

Upvotes: 2

Related Questions