I am trying to use Google Invisible reCAPTCHA, but it is sending empty the g-recaptcha-response
POST parameter when i have multiple forms in the same page. Here is my code:
Google JS
<script src="//google.com/recaptcha/api.js?hl=pt-BR&onload=captchaCallback&render=explicit" async defer></script>
Form 1
<form action="/site/Contact/send" id="form1">
<input type="text" name="nome" required>
<div class="g-recaptcha"
data-sitekey="xxxxxxxxxxxxxxxxxxxxxxxx"
data-callback="form1Callback"
data-size="invisible">
</div>
<button type="submit">Send</button>
</form>
Form 2
<form action="/site/Contact/send" id="form2">
<input type="text" name="nome" required>
<div class="g-recaptcha"
data-sitekey="xxxxxxxxxxxxxxxxxxxxxxxx"
data-callback="form2Callback"
data-size="invisible">
</div>
<button type="submit">Send</button>
</form>
My JS (Based on this answer]
$(document).ready(function() {
window.captchaCallback = function(){
$('.g-recaptcha').each(function(index, el) {
var attributes = {
'sitekey' : $(el).data('sitekey'),
'size' : $(el).data('size'),
'callback' : $(el).data('callback')
};
grecaptcha.render(el, attributes);
});
};
window.form1Callback = function(){
$('#form1').submit();
};
window.form2Callback = function(){
$('#form2').submit();
};
});
When i submit one of these forms the g-recaptcha-response
parameter is sent empty, as below.
Can someone help me to put it to work, please?
You will need to manually call grecaptcha.execute() to run recaptcha if you are rendering invisible recaptcha in a div element. Also if there are multiple forms with recaptcha, then the grecaptcha.execute() method needs to be called with a widget ID generated for each recaptcha when the grecaptcha.render() method is called.
$(document).ready(function() {
window.captchaCallback = function(){
$('.g-recaptcha').each(function(index, el) {
var attributes = {
'sitekey' : $(el).data('sitekey'),
'size' : $(el).data('size'),
'callback' : $(el).data('callback')
};
$(el).data('recaptcha-widget-id', grecaptcha.render(el, attributes));
});
};
window.form1Callback = function(){
$('#form1').data("recaptcha-verified", true).submit();
};
window.form2Callback = function(){
$('#form2').data("recaptcha-verified", true).submit();
};
$('#form1,#form2').on("submit", function(e){
var $form = $(this);
if ($form.data("recaptcha-verified")) return;
e.preventDefault();
grecaptcha.execute($form.find(".g-recaptcha").data("recaptcha-widget-id"));
});
});