34

I have a registration form with the new google recaptcha widget on it. When a user submits info, we check the validation with javascript and return the problems to the page (ex: "please use a valid phone number"). however, since the page doesn't reload, when the user enters correct info and goes to submit again (without having to do the recaptcha again)...the recaptcha is no longer valid and they can't submit without reloading the page.

is there a good solution to this? can I reload the widget somehow? i tried grecaptcha.render but it didn't really do anything.

EDIT:

When I try to render the widget again, it says "placeholder element must be empty"

I tried emptying the element which seemed to work ($('.g-recaptcha').empty();) and then rendering but it still threw the same error.

Matthew Berman
  • 8,481
  • 10
  • 49
  • 98

11 Answers11

43

The method you are looking for is grecaptcha.reset()

However, in order for this function to work you have to render the reCaptacha explicitly like this : <script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>

Ghislaindj
  • 1,783
  • 14
  • 14
  • 4
    i have this error with this method Invalid ReCAPTCHA client id: undefined – Oleg Abrazhaev Aug 21 '15 at 09:31
  • 3
    just as an added note - if you want to reset a specific recaptcha (in cases where you have multiple recaptcah on a single page you can do so by applying the variable name of each captcha like so `grecaptcha.reset(captcha1)` – jshbrmn Apr 11 '16 at 19:03
  • 1
    Unreal. If you change the name of the `onload` function, you get an error "TypeError: a is null". Why? Do they assume the onload function is `onloadCallback` on `reset()`? – Sean Kendle Feb 01 '17 at 20:50
  • 4
    This information would be helpful if it were in the official Google documentation.... which it's not.... and there isn't an option to offer feedback to Google on their docs.... sad. – PromInc Feb 08 '17 at 20:28
  • And what would be the definition of onloadCallback function? Sorry, but noob to javascript. – Farhad Sep 11 '17 at 12:25
9

I was able to do it just by using:

grecaptcha.reset();
Waqleh
  • 9,741
  • 8
  • 65
  • 103
8

If you are using grecaptcha.render with jQuery, please ensure that you are actualy setting DOM element, instead of jQuery element:

This will work:

grecaptcha.render( $('.g-recaptcha')[0], { sitekey : 'your_key_here' });

but this wont:

grecaptcha.render( $('.g-recaptcha'), { sitekey : 'your_key_here' });
Dejan
  • 794
  • 9
  • 9
8

Personnaly I reset my element html content with

$('#captcha').html('');

after that I reload recaptcha using

$.getScript("https://www.google.com/recaptcha/api.js");

which load recaptcha content on your

<div id="captcha" class="g-recaptcha" data-sitekey="yourSitePublicKey"></div>
linktoahref
  • 7,812
  • 3
  • 29
  • 51
Yacine MEDDAH
  • 1,211
  • 13
  • 17
  • Using reset method is better, but if you need to reset already automatically rendered recaptcha in page where there are more than 1 widgets, setting inner html to empty did the work for me. (+1) – Jarda Jan 29 '18 at 11:47
7

Here's some code to accompany @tzafar's answer:

var myCaptcha = null;
function prepCaptcha() {
    if (myCaptcha === null)
        myCaptcha = grecaptcha.render(document.getElementById('my-captcha'), {
            'sitekey': myCaptchaKey,
            'theme': 'light'
        });
    else
        grecaptcha.reset(myCaptcha);
}

In my case, my-captcha is the id of a div inside of a Bootstrap modal. I run prepCaptcha() in the event handler for the modal's shown.bs.modal event. The first time, it initializes the captcha. On subsequent shows of the modal, it resets it.

Also, note that you can quickly verify that you're getting a new captcha by printing the completed captcha's value:

console.log(grecaptcha.getResponse(myCaptcha));

You shouldn't see the same value twice.

Mike Spear
  • 832
  • 8
  • 13
  • It is very strange, in one site I've used it in this way and it's working: grecaptcha.render('RecaptchaField1', {'sitekey' : 'mySiteKey'}); but in another site it wasn't working and I had to use in your way: grecaptcha.render(document.getElementById('RecaptchaField1'), {'sitekey' : 'mySiteKey'}); – ivva Sep 26 '16 at 19:39
  • u guys save my time thanks – funbrain9 Apr 22 '22 at 03:14
3

your recaptcha render js event should be called only once in the script, your recaptcha code is not valid if grecaptcha.render js event called second time in script. You should have to check your code so it should not call the grecaptcha.render function second time on validation check.

OR

In console, You will see a Uncaught ReferenceError: Recaptcha is not defined error message, which indicates the problem with the reCAPTCHA script. This is caused due to a bad url in the page - http://api.recaptcha.net/js/recaptcha_ajax.js . Google has updated the reCAPTCHA and moved the location of the script to http://www.google.com/recaptcha/api/js/recaptcha_ajax.js .

also check this post

http://www.instructables.com/id/Fix-reCAPTCHA-errors-on-Instructables/

and this post

Uncaught ReferenceError: Recaptcha is not defined

Community
  • 1
  • 1
tzafar
  • 674
  • 3
  • 12
  • 1
    I don't actually render it twice. I render it once but when I submit the form and get a 422 error (because another field is incorrect), when i try to submit a second time with a valid field, it says the recaptcha is not correct. – Matthew Berman Dec 29 '14 at 19:35
1

If you're using WordPress, make sure you don't have another reCaptcha plugin installed...that was the issue for me.

Elon Zito
  • 2,872
  • 1
  • 24
  • 28
0

Try calling the reload() function within ReCaptcha (version 1):

Recaptcha.reload();

How to Reload ReCaptcha using JavaScript?

Community
  • 1
  • 1
StaticVoid
  • 1,539
  • 10
  • 11
  • whenever I try this from the console, it says Recaptcha isn't a function. am i doing it wrong? – Matthew Berman Dec 29 '14 at 22:28
  • @JeremyF. Well thanks for the downvote for an update a year later... Why should anyone answer when it will be deprecated at a later date, just to have someone come along and give them a negative remark. – StaticVoid Mar 24 '16 at 17:04
  • @StaticVoid Well simply because I didn't find relevant to see the answer so high in the list for current users to see. Plus without my comment someone not knowing about the version difference would know which is which at first glance. This was my case when I got here searching about this issue. Sorry I didn't mean to offend you ! – Jeremy F. Mar 25 '16 at 10:16
  • @JeremyF. No offense taken. I just see it as redundant to go through the site downvoting everything because a new version of it came out... Carry on. – StaticVoid Apr 04 '16 at 13:32
0

if you are using new recaptcha 2.0 use this: for code behind:

ScriptManager.RegisterStartupScript(this, this.GetType(), "CaptchaReload", "$.getScript(\"https://www.google.com/recaptcha/api.js\", function () {});", true);

for simple javascript

<script>$.getScript(\"https://www.google.com/recaptcha/api.js\", function () {});</script>
Sara Khan
  • 325
  • 1
  • 4
  • 9
0

I had same problem with excelwebzone/recaptcha-bundle for Symfony2. Basicly is says that recaptcha was loaded in past to your DOM and placeholder that should be empty was full.

Those bundles dont have settings for explicit callbacks so you have to make sure that placeholder or even whole form is empty before you load recaptcha.

And mine was stuck in DOM cause i was loading it with AJAX. On second call it was there.

You can simply use $('#your-div-with-form').html('')

0
<script>
function cform(token) {
$.ajax({
type: 'POST',
url: 'contact_chk.php',
data: $('#cform').serialize(), 
success: function(response) {
grecaptcha.reset();
$("#con_msg").html(response);
document.getElementById("name").value='';
document.getElementById("subject").value='';
document.getElementById("email").value='';
document.getElementById("phone").value='';
document.getElementById("message").value='';
},
error: function(response) {
grecaptcha.reset();
$("#con_msg").html('Try Again...');
}
});
}
</script>
<script src='https://www.google.com/recaptcha/api.js'></script>