I am using the recaptcha gem. Rails 5.2.
I have the following form:
= simple_form_for @quote_request_form, url: quote_requests_path, html: {id: "invisible-recaptcha-form"} do |f|
.form-group
= f.input :name, label: false, placeholder: 'First and Last Name',
.form-group.actions.mt-5
button.btn.btn-primary.btn-lg.btn-block#submit-btn Submit
= invisible_recaptcha_tags ui: :invisible, callback: 'submitInvisibleRecaptchaForm'
I have added the following javascript for the form:
javascript:
document.getElementById('submit-btn').addEventListener('click', function (e) {
e.preventDefault();
grecaptcha.execute();
});
var submitInvisibleRecaptchaForm = function () {
document.getElementById("invisible-recaptcha-form").submit();
};
I check the value from the recaptcha in my controller as follows:
if verify_recaptcha(model: @quote_request_form) && @quote_request_form.save
redirect_to quote_confirm_path, notice: "Your quotation request is being processed"
else
render :new
end
It all works as long as I use the e.preventDefault(); line. If I remove this line I get a failure with the recaptcha and I can see in the parameters that the recaptcha attriburte is sending in blank data.
I don't understand why I need it as none of the documentation specify it. So I'm doing something wrong but I can't figure it out.
Can anyone see how I can fix this?
You need the e.preventDefault()
statement otherwise the form will be submitted before recaptcha executes the callback.
This happens because <button>
with no type attribute has submit
as the default value/ behavior. If you look at recaptcha documentation, the <button>
tag has the type attribute defined as button
, which has no behavior associated, thus no action happens when you click at it.
Returning to your case, either you keep the e.preventDefault()
statement or you set the type attribute as button
:
.form-group.actions.mt-5
button.btn.btn-primary.btn-lg.btn-block#submit-btn type="button" Submit
= invisible_recaptcha_tags ui: :invisible, callback: 'submitInvisibleRecaptchaForm'