Reputation: 1625
I have a form containing a button that will fire google invisible recaptcha. the html page I'm using looks like this:
<html>
<head>
<script src="https://www.google.com/recaptcha/api.js?onload=onLoadRecaptcha&render=explicit" async defer></script>
</head>
<body>
<form method="post" id="signup_form">
<input type="text" name="fullname" value=""/>
<div class="g-recaptcha"
id="formSignup-recaptcha"
data-sitekey="<?php echo $sitekey; ?>"
data-callback="onSubmitFormSignupUser"
data-size="invisible">
</div>
<button type="button" name="submitBtn" id="submitBtn">Submit</button>
</form>
</body>
</html>
but when I click the #submitBtn
, I need to run an validation process using ajax to make sure that all the required fields are filled correctly before the google recaptcha is called/executed. here's the javscript code I'm using:
var widgetId = '';
var onLoadRecaptcha = function() {
widgetId = grecaptcha.render('submitBtn', {
'sitekey': $('#formSignup-recaptcha').attr('data-sitekey'),
'callback': onSubmitFormSignupUser,
});
};
var onSubmitFormSignupUser = function() {
validateForm('#formSignupUser')
};
var doSubmitFormSignupUser = function(target) {
var postData = $(target);
$.ajax({
url: '/signup_user',
type: 'post',
data: postData,
dataType: 'json',
success: function(res) {
if (res.status) {
window.location.href = '/home/signup_success';
} else {
console.log(res.message);
}
},
error: function(err) {
console.log('error', err.responseText);
},
complete: function() {
grecaptcha.reset(widgetId);
}
});
});
var validateForm = function(target) {
var myData = $(target).serializeArray();
$.ajax({
url: '/is_validated',
type: 'post',
data: myData,
dataType: 'json',
async: false,
success: function(res) {
if (res.status) {
doSubmitFormSignupUser(target);
} else {
console.log('message', res.message);
}
},
error: function(err) {
console.log('error', err.responseText);
},
complete: function() {
grecaptcha.reset(widgetId);
}
});
}
$('body').on('click', '#submitBtn', function(e) {
e.preventDefault();
grecaptcha.execute(widgetId);
});
and here's my php code:
function is_validated()
{
$response = [
'status' => 0,
'message' => '',
];
echo json_encode($response);
}
function signup_user()
{
echo 'thank you for signing up';
}
somehow that code doesn't work.. whenever I click on #submitBtn
, the google recaptcha automatically appears asking the user to select all images with a bus or the likes. I don't know what is wrong with my code.. can anyone help?
Upvotes: 0
Views: 1086
Reputation: 6359
I don't know, Why are you using server side form validation with ajax.
Because, in below line you are executing the reCaptcha
right after click the button.
$('body').on('click', '#submitBtn', function(e) {
e.preventDefault();
grecaptcha.execute(widgetId);
});
If you want to execute reCaptcha
after the ajax request
, Remove the line grecaptcha.execute(widgetId);
from above block. And put here,
complete: function() {
grecaptcha.execute(widgetId);
}
Upvotes: 1