I am validating forms using this:
$(document).ready(function() {
$('form.brochure_form').validate();
});
I currently have invisible recaptcha being dynamically created with this (this works without validation).
function onloadCallback() {
var count = 1;
$(".g-recaptcha").each(function() {
var object = $(this);
var theid = object.attr('id');
var widgetID = "recaptcha_" + count;
grecaptcha.render("recaptcha_" + count, {
"sitekey" : "SITEKEY",
"callback" : function(token) {
object.parents('form').find(".g-recaptcha-response").val(token);
// VALIDATE HERE
if(object.parents('form').valid() == true){
object.parents('form').submit();
} else {
grecaptcha.reset(widgetID);
};
}
});
count++;
});
}
At the minute this is how it works;
- Form validates with reCaptcha
- Form runs jQuery validate
- Submits
The issue is if form validates #1 and then fails on #2 I need to reset reCaptcha to do it again (this is where I am struggling, as I can't pass widgetID correctly - if I leave this blank it works for the first form only)
My ideal scenario would be to switch #1 and #2 but I couldn't get this working either.
Also, the above currently returns
Uncaught (in promise) null
Here's HTML for reference (Stripped out all fields as it's quite a big form)
<form id="form--brochure1" class="brochure_form " action="" method="post">
<input type="submit" value="Submit" class="g-recaptcha" id="recaptcha_1" data-badge="inline">
</form>
<form id="form--brochure2" class="brochure_form " action="" method="post">
<input type="submit" value="Submit" class="g-recaptcha" id="recaptcha_2" data-badge="inline">
</form>
The page just refreshes on submit but I am doing server-side validation as follows:
if(isset($_POST['g-recaptcha-response'])) {
$secretKey = 'SECRETKEY';
$response = $_POST['g-recaptcha-response'];
$remoteIp = $_SERVER['REMOTE_ADDR'];
$reCaptchaValidationUrl = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$response&remoteip=$remoteIp");
$result = json_decode($reCaptchaValidationUrl, TRUE);
if($result['success'] == 1) {
// EMAIL SENT, DATABASE UPDATED ETC HERE
}
}