Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google reCaptcha reset doesn't work

I want to reset Google reCaptcha widget when I submit my form via AJAX and have some input errors or form is sent. I'm using multiple widgets on the same page so I render these widgets explicitly.

My HTML code:

<div class="g-recaptcha" id="recaptcha-1"></div> <div class="g-recaptcha" id="recaptcha-2"></div> ... <div class="g-recaptcha" id="recaptcha-20"></div> 

Loading widget

<script src="https://www.google.com/recaptcha/api.js?onload=reCaptchaCallback&render=explicit&hl=en" async defer></script> <script>     var reCaptchaCallback = function() {         var elements = document.getElementsByClassName('g-recaptcha');         for (var i = 0; i < elements.length; i++) {             var id = elements[i].getAttribute('id');             grecaptcha.render(id, {                 'sitekey' : 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'             });         }     }; </script> 

After submit form:

var id = $('.g-recaptcha', form).attr('id'); grecaptcha.reset(id); 

Form is the instance of the submitted form.

Everything works fine when form is fill correctly. But reCaptcha doesn't reset or reload. It try this grecaptcha.reset() but no results.

Any idea?

like image 369
quarky Avatar asked May 04 '15 20:05

quarky


People also ask

How do I reset Google reCAPTCHA?

For reCaptcha v2, use: grecaptcha. reset();

How do I reset multiple reCAPTCHA?

reset(recaptcha2); To be clear, you have to save the return values of grecaptcha. render(), and pass in those vars to the reset() function. Passing in the string ID of the captcha doesn't work.


2 Answers

The grecaptcha.reset() method accepts an optional widget_id parameter, and defaults to the first widget created if unspecified. A widget_id is returned from the grecaptcha.render() method for each widget created. So you need to store this id, and use it to reset that specific widget:

var widgetId = grecaptcha.render(container); grecaptcha.reset(widgetId); 

See here.

like image 88
levi Avatar answered Sep 19 '22 15:09

levi


You are passing the wrong id.

$('.g-recaptcha', form).attr('id');

Your selector will capture all 20 reCaptcha widget, but only return a single DOM id (the first reCaptcha). So your code is actually resetting the first recaptcha.

like image 37
Jason Avatar answered Sep 17 '22 15:09

Jason