While using reCaptcha, I faced a problem. In code, using AJAX to submit form. Before submitting I need to check if the fields are filled or not. If fields are not filled, submit should not happen.
In this case, if textfields are not filled, it will give an alert.
The problem is after the rejection of invalid post, the submit button stops working for like 2 or 3 minutes and there is no error given by reCaptcha. After the period of time, reCaptcha starts working again and submit button works.
<form id="contact-form" method="post" action="javascript:void(0)">
<input type="text" placeholder="Name" id="name">
<input type="text" placeholder="E-Mail" id="email">
<textarea placeholder="Message" id="message">/textarea>
<button class="g-recaptcha pull-right" data-sitekey="#your-site-key" data-callback="sendData" type="submit"> SEND <i class="flaticon-origami34"></i> </button>
</form>
Javascripts :
function sendData(){
console.log('send data - '); // --> works
//send datas:
$("#contact-form").submit();
};
$('#contact-form').on("submit", function() {
console.log('clicked submit'); // --> works
name = $('#name').val().replace(/<|>/g, ""), // prevent xss
email = $('#email').val().replace(/<|>/g, ""),
msg = $('#message').val().replace(/<|>/g, "");
if (name == '' || email == '' || msg == '') {
alert("Please fill all areas !");
} else {
console.log('captcha response: ' + grecaptcha.getResponse()); // --> captcha response:
// ajax to the php file to send the mail
$.ajax({
type: "POST",
url: "SaveContact.php",
data: "email=" + email + "&name=" + name + "&msg=" + msg + "&g-recaptcha-response=" + grecaptcha.getResponse()
}).done(function(status) {
if (status == "ok") {
// clear the form fields
$('#name').val('');
$('#email').val('');
$('#message').val('');
}
});
}});
According to the documentation, you can also call grecaptcha.reset(opt_widget_id);
, where opt_widget_id
is optional and will default to the first recaptcha widget created.
Then you need to reset cooldown of invisible recaptcha, you could use a hack like this
var recaptchaIframe = document.querySelector('.grecaptcha-badge iframe');
recaptchaIframe.src = recaptchaIframe.src;
I don't have a better solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With