I’ve just implemented reCaptcha v3 on a form (the contact form of my website which was using reCaptcha v2 got hacked, so I have setup a test form to get the implementation right before I roll out).
Here’s the script that is handling all the reCaptcha stuff:
$('#contactForm').submit(function(event){
event.preventDefault();
grecaptcha.ready(function() {
grecaptcha.execute('[My_Site_Key]', {action: 'contactForm'}).then(function(token) {
$('#contactForm').prepend('<input type="hidden" name="g-recaptcha-response" value="' + token + '">');
console.log(token)
$('#contactForm').unbind('submit').submit();
});
});
});
Obviously, [My_Site_Key] has the real site in it, I’ve just removed it here.
When I click SUBMIT on the form, I see the token logged to the console, but to get the form to actually submit (and trigger the action), I need to click the submit button a second time. When I do click a second time, the form action is triggered and I get the test email that the server-side script generates upon getting a successful reCaptcha response.
I thought that the whole point of the .unbind(‘submit’).submit() was that it removed the event handler binding (and thus, effectively reverses the effect of the event.preventDefault() ) and then submitted the form, but it doesn’t seem to be doing so.
Anyone got any suggestions how this can be edited so that I don’t need to click the submit button twice to get the form to actually submit?
Thanks.
2
Answers
It seems that if you have the submit button named "submit", it causes the submit button to need to be clicked twice to make this work. After talking to a friend who had the same issue, I've renamed the submit button to be name="submit2" and now it works as expected.
An HTMLFormElement has a property for every named element (be it a button or an input field) inside it. If you name such an element
submit
, this element overwrites theHTMLFormElement::submit()
function so that you can no longer programmatically submit the form.You can still submit it interactively by pressing the submit button, however.