I have two form on one page and I'm currently using google captcha v2 but I want to upgrade the form to captcha v3, is there an easey way to do this.
From the documentation I read that using this code will work, but it only works for one form and it ignores my first click that check all the required field on my forms.
<script>
function onClick(e) {
e.preventDefault();
grecaptcha.ready(function() {
grecaptcha.execute('reCAPTCHA_site_key', {action: 'submit'}).then(function(token) {
// Add your logic to submit to your backend server here.
});
});
}
</script>
<form role='form' method='POST' id='myForm' enctype='multipart/form-data' class='hiddenContent myForm2'>
<center><div id='myCaptchaDiv1'></div></center>
<div class='form-row'>
<div class='col-12' id='btn-subtmit'>
<button class='btn btn-primary btn-controls'>Submit <i class='fas fa-check'></i></button>
</div>
</div>
</form>
<form role='form' method='POST' id='myForm' enctype='multipart/form-data' class='hiddenContent myForm2'>
<center><div id='myCaptchaDiv2'></div></center>
<div class='form-row'>
<div class='col-12' id='btn-subtmit'>
<button class='btn btn-primary btn-controls'>Submit <i class='fas fa-check'></i></button>
</div>
</div>
</form>
<script type="text/javascript">
var CaptchaCallback = function() {
grecaptcha.render('myCaptchaDiv1', {'sitekey' : 'myoid'});
grecaptcha.render('myCaptchaDiv2', {'sitekey' : 'myoid'});
};
</script>
<script src="https://www.google.com/recaptcha/api.js?onload=CaptchaCallback&render=explicit" async defer></script>
Have you added an event listener to both forms? The forms have to have unique IDs (you posted them both as 'myForm'), and make sure you register the onClick
callback like so:
const form1 = document.getElementById('myForm1');
const form2 = document.getElementById('myForm2');
form1.addEventListener('submit', onClick);
form2.addEventListener('submit', onClick);
Any form validation that you might to do (checking the required fields), you can do before grecaptcha.ready(...)
. An example:
<script>
function onClick(e) {
e.preventDefault();
// DO FIELD CHECKS. If invalid, then return;
...
grecaptcha.ready(function() {
grecaptcha.execute('reCAPTCHA_site_key', {action: 'submit'}).then(function(token) {
// Add your logic to submit to your backend server here.
});
});
}
</script>