SOLVED

GTM Form Event Listener is overriding onSuccess script

Go to solution
dleopold
Level 2

GTM Form Event Listener is overriding onSuccess script

I've looked through a bunch of posts on here, but can't find one that's entirely relevant to my situation.

 

I'm trying to create an onSuccess script where the user will stay on the page if certain criteria is met and a second form will show, but if they don't meet the criteria, they will be redirected to a Thank You page (which is how the form functions today).

 

Setting 'return false' has no effect, and from researching in here, I believe it's our form event listener on GTM that is causing any custom onSuccess code to be overridden. The form will either redirect to the Thank You page that is set up on the Marketo side, or if I change that to 'stay on page', the page refreshes entirely instead of just hiding the form.

 

If I remove the event callback that is in the GTM code, everything works as it is supposed to, BUT it breaks our other forms on the website from submitting for some reason.

 

Is there anyway to override the GTM event callback?

 

Here is my form code that is loading from a JS file on our Wordpress site:

 

<script>
function loadMktoForm() {
( ( $ ) => {

let criteriaMet = false;

MktoForms2.loadForm(
domain_name,
munchkin_id,
form_id,
( form ) => {


form.onSubmit( () => {

// IF ORGANIZATION TYPE MEETS CRITERIA, SET VARIABLE TO CONTROL WHAT THE SUBMIT BUTTON WILL DO

var field_val = form.getValues()['Organization_Type__c'];

if ( (field_val === 'Medical Practice') || (field_val === 'Health System') ) {
criteriaMet = true;

}
} );

// Add an onSuccess handler
form.onSuccess( () => { // values, followUpUrl


if ( criteriaMet === true ) {
form.getFormElem().hide();

// Return false to prevent the submission handler continuing with its own processing
return false;
}

else {
// Take the lead to a different page on successful submit, ignoring the form's configured followUpUrl
location.href = "/thank-you/";

// Return false to prevent the submission handler continuing with its own processing
return false;
}


// Return false to prevent the submission handler continuing with its own processing
return false;


} );

}
);


} )( jQuery );
}

// Init the marketo form on page load
loadMktoForm();
</script>

 

 

And here is the GTM code:

 

<script>
/**
 * push Marketo form events and values to Google Tag Manager via the data layer
 * uses the Marketo Forms 2.0 API
 */
(function marketoFormListener (MktoForms2) {
    "use strict";
    /**
     * helper function to push invalid Marketo field errors to GTM
     * @returns {undefined}
     */
    function waitForError () {
        var element, input, mktoErrorMsg;
        // check for error message
        element = document.querySelector(".mktoErrorMsg");
        if (element) {
            mktoErrorMsg = element.textContent || element.innerText;
            // look for invalid input
            input = document.querySelector("input.mktoInvalid, .mktoInvalid input");
            window.dataLayer.push({
                "event": "mkto.form.error",
                "mkto.form.error.message": mktoErrorMsg,
                "gtm.element": input,
                "gtm.elementClasses": input && input.className || "",
                "gtm.elementId": input && input.id || "",
                "gtm.elementName": input && input.name || "",
                "gtm.elementTarget": input && input.target || ""
            });
        }
    }
 
    if (MktoForms2) {
        MktoForms2.whenReady(function handleReady (form) {
            window.dataLayer.push({
                "event": "mkto.form.ready",
                "mkto.form.id": form.getId(),
                "mkto.form.submittable": form.submittable(),
                "mkto.form.allFieldsFilled": form.allFieldsFilled(),
                "mkto.form.values": form.getValues()
            });
 
            form.onValidate(function handleValidate (valid) {
                window.dataLayer.push({
                    "event": "mkto.form.validate",
                    "mkto.form.valid": valid
                });
                // wait for the error message to appear
                setTimeout(waitForError, 0);
            });
 
            form.onSubmit(function handleSubmit (thisForm) {
                var button;
                button = form.getFormElem().find("button[type=\"submit\"]");
                window.dataLayer.push({
                    "event": "mkto.form.submit",
                    "mkto.form.id": form.getId(),
                    "mkto.form.submittable": form.submittable(),
                    "mkto.form.allFieldsFilled": form.allFieldsFilled(),
                    "mkto.form.values": form.getValues(),
                    "mkto.form.button": {
                        "classes": button.attr("class"),
                        "text": button.text(),
                        "type": "submit"
                    }
                });
            });
 
            form.onSuccess(function handleSuccess (values, followUpUrl) {
                window.dataLayer.push({
                    "event": "mkto.form.success",
                    "mkto.form.id": form.getId(),
                    "mkto.form.values": values,
                    "mkto.form.followUpUrl": followUpUrl,
                    "eventCallback": function () {
                      document.location.href = followUpUrl;
                    },
                    "eventTimeout" : 3000
                  });
                  return false;
             });
 
        });
 
        MktoForms2.whenRendered(function handleRendered (form) {
            window.dataLayer.push({
                "event": "mkto.form.rendered",
                "mkto.form.id": form.getId(),
                "mkto.form.submittable": form.submittable(),
                "mkto.form.allFieldsFilled": form.allFieldsFilled(),
                "mkto.form.values": form.getValues()
            });
        });
    }
})(window.MktoForms2);
  </script>

 

 

Thank you in advance!

Tags (1)
1 ACCEPTED SOLUTION

Accepted Solutions
dleopold
Level 2

Re: GTM Form Event Listener is overriding onSuccess script

What would be the correct implementation then? 

 

Not sure if I'm thinking about this wrong, but would I put in a conditional statement in the GTM code? Something like 

    form.onSuccess(function handleSuccess (values, followUpUrl) {
                window.dataLayer.push({
                    "event": "mkto.form.success",
                    "mkto.form.id": form.getId(),
                    "mkto.form.values": values,
                    "mkto.form.followUpUrl": followUpUrl,
                    "eventCallback": function () {
                        if ( form.getId() != 3579) {
                      document.location.href = followUpUrl;
                        }
                    },
                    "eventTimeout" : 3000
                  });
                  return false;
             });

View solution in original post

8 REPLIES 8
SanfordWhiteman
Level 10 - Community Moderator

Re: GTM Form Event Listener is overriding onSuccess script

There shouldn't be any confusion here. The code is doing exactly what you'd expect, every time (that is, there's no race condition or randomness).

If you don't want the page to redirect for certain form IDs, then exclude them from the GTM eventCallback, which currently redirects for all forms.
dleopold
Level 2

Re: GTM Form Event Listener is overriding onSuccess script

How do I exclude them from the GTM callback? Is that a line of code that needs to be added in there? Or an exception that needs to be added to the entire trigger event in GTM?

dleopold
Level 2

Re: GTM Form Event Listener is overriding onSuccess script

Actually, I may have figured it out. We use 1 of 2 JS files for all the forms on the site, so on the other JS file, I added an onSuccess script the same way I'm doing in the first one, just without the selection logic. Having it defined there is allowing me to remove the event callback in GTM then and still have everything redirect as it's supposed to.

 

form.onSuccess( (values, followUpUrl) => { // values, followUpUrl

                    location.href = followUpUrl;
				} );

 

SanfordWhiteman
Level 10 - Community Moderator

Re: GTM Form Event Listener is overriding onSuccess script

That won't do it. The eventCallback isn't the same as the form onSuccess. They respond to different events. If you're still sending the GTM event, you need the GTM-specific eventCallback.
dleopold
Level 2

Re: GTM Form Event Listener is overriding onSuccess script

What would be the correct implementation then? 

 

Not sure if I'm thinking about this wrong, but would I put in a conditional statement in the GTM code? Something like 

    form.onSuccess(function handleSuccess (values, followUpUrl) {
                window.dataLayer.push({
                    "event": "mkto.form.success",
                    "mkto.form.id": form.getId(),
                    "mkto.form.values": values,
                    "mkto.form.followUpUrl": followUpUrl,
                    "eventCallback": function () {
                        if ( form.getId() != 3579) {
                      document.location.href = followUpUrl;
                        }
                    },
                    "eventTimeout" : 3000
                  });
                  return false;
             });
SanfordWhiteman
Level 10 - Community Moderator

Re: GTM Form Event Listener is overriding onSuccess script

Well done! That's exactly what I was getting at.
dleopold
Level 2

Re: GTM Form Event Listener is overriding onSuccess script

Thank you! One last question as I'm getting to the next phase of the code (I can start a new thread if needed):

I'm trying to use the code found here to load the next form: https://nation.marketo.com/t5/product-discussions/on-form-submit-can-i-send-the-user-to-another-form... How do I add the conditional statement to that to say if the criteria is met, load the second form, otherwise go to the Thank You page? 

SanfordWhiteman
Level 10 - Community Moderator

Re: GTM Form Event Listener is overriding onSuccess script

Yes, can you start a new thread for that?