I'm trying to implement the new invisible reCAPTCHA, from Google. It's all working perfectly, but my forms always have two submit buttons, that does different things with the input.
I tried to simply add another <button> in my form, but reCAPTCHA only recognizes the first one in code.
I can't think of any reason that would prevent the other button to work properly. Here is a simple example of what I tried:
<form action="page.php" method="POST">
<input type="text" value="textfield"/><br/>
<button class="g-recaptcha" data-sitekey="mysitekey" data-callback='onSubmit'
value="anaction">An action</button>
<button class="g-recaptcha" data-sitekey="mysitekey" data-callback='onSubmit'
value="anotheraction">Another action</button>
</form>
I usually tell apart the two buttons by making an isset on the POST values. Here it doesn't seem to work with the second button. If I switch the two lines, it will make the other button submit properly.
If someone has an idea about this, I'll thank him for enlightments.
Thank you :)
Stash the token in a hidden field and use it instead of the g-recaptcha-response value to send your verification request. You can distinguish between the two submissions by saving the action item in the JSON return object. I have no idea why this works, by the way.
<head>
...
<script src="https://www.google.com/recaptcha/api.js"></script>
<script>
function onSubmit(token) {
document.getElementById("token").value = token;
document.getElementById("form").submit();
}
</script>
...
</head>
<body>
...
<form id="form" action="page.php" method="POST">
<input type="hidden" id="token" name="token">
...
<button type="submit" class="g-recaptcha" data-sitekey="..."
data-callback="onSubmit" data-action="action">An Action</button>
<button type="submit" class="g-recaptcha" data-sitekey="..."
data-callback="onSubmit" data-action="anotheraction">Another Action</button>
</form>
I had same issue and I fixed it like below:
<button type="submit" class="g-recaptcha"
id="captcha1"
data-sitekey="YOUR_SECRETKEY"
data-callback="sendData">button</button>
<button type="submit" class="g-recaptcha"
id="captcha2"
data-sitekey="YOUR_SECRETKEY"
data-callback="sendData">button</button>
<script type="text/javascript">
$( document ).ready(function() {
$(".g-recaptcha").each(function() {
var object = $(this);
grecaptcha.render(object.attr("id"), {
"sitekey" : "YOUR_SITEKEY",
"callback" : function(token) {
object.parents('form').find(".g-recaptcha-response").val(token);
object.parents('form').submit();
}
});
});
}
);
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With