Google ReCaptcha v3 - form.addHiddenFields not working

Gursimran_Chand
Level 4

Google ReCaptcha v3 - form.addHiddenFields not working

I am trying to implement Google Recaptcha v3 in our instance. However, I am stuck with passing the Google Response back to Marketo using form.addHiddenFields (it is not working as expected - empty value is being passed to Marketo for some reason).

 

Google docs recommend adding this (https://developers.google.com/recaptcha/docs/v3). My sample code is below which is not working:

 

MktoForms2.whenReady(function (form) {
    var response;
    form.onValidate(function () {
        grecaptcha.ready(function () {
            grecaptcha.execute('KEY', {
                action: 'submit'
            }).then(function (token) {
                response = token;
                console.log(response);
                console.log("RESPONSE");
                form.addHiddenFields({
                    'RecaptchaResponse': response
                });
            });
        });
        form.addHiddenFields({
            'TestField': 'TEST VALUE'
        });
    });
});

 

 

 A few things:

1. console.log(response) shows the correct response value received from Google.

2. form.addHiddenFields({'TestField':'TEST VALUE'}) works as expected (when adding it outside grecaptcha.execute)

3. form.addHiddenFields({'RecaptchaResponse':response}) is not working as expected. I can't figure out why.

 

Any help is appreciated.

@SanfordWhiteman 

1 REPLY 1
SanfordWhiteman
Level 10 - Community Moderator

Re: Google ReCaptcha v3 - form.addHiddenFields not working


3. form.addHiddenFields({'RecaptchaResponse':response}) is not working as expected. I can't figure out why.


By "not as expected" do you mean the form submits without the new field?

 

That actually should be expected  with your current code!

 

See, grecaptcha.execute is an asynchronous action. And you're not waiting for it to complete, so the regular submit process continues.

 

You have to set form.submittable(false) and when .then() is called, set form.submittable(true) and allow the submit to continue.

 

I've prepared the client-side recipe here: MktoForms2 :: reCAPTCHA v3 v1.1.1

 

And then of course there's the server-side (webhook) config, which has its own cases to consider. I am supposed to write the whole thing up on the Products blog, but unfortunately haven't yet.