John Davidson

php - Laravel Recaptcha v3 returns nothing

0 comments
Message:


I am trying to add a recaptcha to one of my forms and I have no clue why it is no working.


In my form


... form ...
@if($settings->recaptcha_enabled && !empty($settings->recaptcha_site_key) && !empty($settings->recaptcha_secret_key))
{!! Form::hidden('g-recaptcha-response', null, [ 'id' => 'recaptcha', 'data-sitekey' => $settings->recaptcha_site_key]) !!}
@endif
... form ...

On the bottom of my page (the output is in HTML and has proper values as site key etc, so the condition is not a problem)


@if($settings->recaptcha_enabled && !empty($settings->recaptcha_site_key) && !empty($settings->recaptcha_secret_key))
<script src="https://www.google.com/recaptcha/api.js?render={!! $settings->recaptcha_site_key !!}"></script>

<script>
function onClick(e) {
e.preventDefault();
grecaptcha.ready(function() {
grecaptcha.execute('{!! $settings->recaptcha_site_key !!}', {action: 'submit'}).then(function(token) {
console.log('test1');
if (token) {
console.log('test2')
document.getElementById('recaptcha').value = token;
}
});
});
}
</script>
@endif

I can see a recaptcha badge on the bottom right corner so I suppose It has been loaded properly.


But when I click the submit form (with preserve log and enabled logging on the server) I am receiving NULL in g-recaptcha-response object. I´ve been looking for that hidden input change (there should be some addition of some token right before submitting the form I suppose) but that input wont change.


I am not posting here my backend part of validation (which should be pretty easy) because I have not managed the first part- getting recaptcha token from FE at first time.



My Answer:
It looks like you are missing the `onClick` function call in your form submit button. You need to call the `onClick` function when the form is submitted in order to execute the reCAPTCHA and get the token.

You can add the `onClick` function to your form submit button like this:

html



This way, when the form is submitted, the `onClick` function will be called and the reCAPTCHA token will be retrieved and added to the hidden input field before the form is actually submitted.

Make sure to add this `onClick` function call to your form submit button and try submitting the form again. This should solve the issue of not getting the reCAPTCHA token in the `g-recaptcha-response` object.

Rate this post

5 of 5 based on 5098 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us