Getting issue on AJAX Form Submission with reCaptcha V3

Hi There,

We have implemented reCaptcha V3 on one of the forms on our website.

However, the ajax submission seems not working anymore and we are getting output like the attached screenshot below on form submission.

It’s working fine with the reCaptcha V2, can you please guide us how to make the ajax submission working with the reCaptcha V3?

Not sure if this helps, but @James posted this in the Slack group:

I’ll try and get a working demo up for everyone to reference too…

Was there ever an updated demo for this issue? I’m kinda stuck…

The javascript that gets generated by the form for ReCaptcha 3 is:

'use strict';
grecaptcha.ready(function () {
	function c(a) {
		grecaptcha.execute("xxxxxxxxxxxx", {
			action: 'general_form_{{this.Alias | replace: "-","_"}}'
		}).then(function (b) {
			document.querySelector(".g-recaptcha-response-v3-{{this.Alias}}").value = b;
			a && a()
		})
	}
	window.customFormSubmit = new Event("customFormSubmit");
	let a = document.querySelector(".g-recaptcha-response-v3-{{this.Alias}}").closest("form");
	if (null != a) {
		let d = !0,
			b = 0;
		a.onsubmit = function () {
			event.preventDefault();
			if (d) return b++, d = !1, c(function () {
				let c = document.getElementById("paymentFields_" + a.getAttribute("name"));
				c ? "true" === c.dataset.paymentEnabled ? (a.dispatchEvent(window.customFormSubmit), b = 0, d = !0) : a.submit() : a.submit()
			}), !1;
			0 < b && b++;
			if (1 < b) return alert("Form submission is in progress."), !1
		}
	} else c()
});

Where exactly does “executeRecaptcha(function(){onMyFormSubmit()});” go?!

Sorry, it’s the end of the day and I’m just not getting it. Any help is appreciated!

I’ve just seen the ping on this…

It looks like the v3 code got updated on treepl side and so the calls need to be updated…

here is the v3 script that is generated by Treepl. I have adjusted it to call the below function , rather than just a.submit()

You only need to update the function call the rest is untouched.

	<script>
 'use strict';grecaptcha.ready(function(){function c(a){grecaptcha.execute("XXXXXXX",{action:'general_form_{{this.Alias | replace: "-","_"}}'}).then(function(b){document.querySelector(".g-recaptcha-response-v3-{{this.Alias}}").value=b;a&&a()})}window.customFormSubmit=new Event("customFormSubmit");let a=document.querySelector(".g-recaptcha-response-v3-{{this.Alias}}").closest("form");if(null!=a){let d=!0,b=0;a.onsubmit=function(){event.preventDefault();if(d)return b++,d = !1,c(function(){let c = document.getElementById("paymentFields_"+a.getAttribute("name"));c?"true"===c.dataset.paymentEnabled?(a.dispatchEvent(window.customFormSubmit),b=0,d=!0):onMyFormSubmit():onMyFormSubmit()}),!1;0<b&&b++;if(1<b)return alert("Form submission is in progress."),!1}}else c()}); 	</script>
<input type="hidden" class="g-recaptcha-response-v3-{{this.Alias}}" name="g-recaptcha-response-v3">

and here is the Ajax function (which you should paste below:

<script>
function onMyFormSubmit() {
    var $f = $('#quick_contact_form');
    var $s = $('#quick_contact_form input[type="submit"]');
    var $r = $('#msgResponse');
    var gr3 = document.querySelector('.g-recaptcha-response-v3-{{this.Alias}}').value;
    
    if(!gr3) {
        $r.css('color', 'red').html('reCaptcha not valid. Try Refreshing the page.');
    } else {
        if($f.data("sent")) {
            $r.css('color', 'red').html("Form submission is already in process.");
        } else {
            $f.data("sent", true);
            $s.val("Sending..."); //not nessecery but a much better UX
            $.ajax({
                method: 'POST',
                dataType : "json",
                url: $f.attr('action'),
                data: $f.serialize()
            })
            .done(function(msg) {
                var formResponse = msg;
                if (formResponse.Error == 0) {
                    var output = "";
                    formResponse.Fields.All.forEach(function(field, index) {
                        output += field.Name + ': ' + field.Value + '<br>';
                    });
                    $f.fadeOut(300);
                    $r.css('color', 'green').fadeIn(500).html('<h4>Thank you!</h4><p>' + output + '</p>');
                } else {
                    var errorOutput = "";
                    formResponse.ErrorMessages.forEach(function(err, index) {
                        errorOutput += err + '<br>';
                    });
                    $r.css('color', 'red').fadeIn(500).html(errorOutput);
                    $f.data("sent", false);
                }
            })
            .fail(function(xhr) {
                $r.css('color', 'red').fadeIn(500).html('error'+ xhr);
                $f.data("sent", false);
                return false;
            });
        }
    }
} 
</script>

Please note that this ajax script can be change to suit your needs, ive ripped it form an old form of mine and so it might not be exactly what you need.

I have tested this and the form submits fine, triggers workflows and shows a hidden div on submission with the results.

2 Likes

@James - you are a life saver! We are LITERALLY going live with a site using this today - so your timing couldn’t be better!

Quick point of clarification for others who may stumble upon this post: put the “Ajax function” script at the bottom of the form. The function uses liquid {{this.Alias}} which won’t work in an external javascript file.

Hey @Derek_Barnes
Glad I could help!

And yes with Treepl anything relating to a form should be help within the form container rather than externally. My apologies I should have noted this. Thanks for the pickup :slight_smile:

Also for future ref for anyone else… If you don’t want to list out the json response on success, and would rather just show your own message div, you can comment out the thankyou line and add the below.

...
$f.fadeOut(300);
ADD THIS LINE >  $('#your-hidden-message-div').fadeIn(500);
COMMENT THIS LINE > //$r.css('color', 'green').fadeIn(500).html('<h4>Thank you!</h4><p>' + output + '</p>');
...

Good luck :slight_smile:

1 Like

I echo @Derek_Barnes comments above on reCaptcha V3, your advice helped us overcome an issue on a new client site where we’re using a form and its associated submissions as a rudimentary ‘satisfaction’ survey reporting tool. Cheers and Thank You @James !

1 Like

No Worries @amplify-scott :slight_smile: Glad I could help