Tracking Validated Submissions Using GTM On Mailchimp Embedded Form
Solution 1:
The e.preventDefault()
function only stops the form from submitting, it does nothing to check for validation and without having anything after it, nothing will happen.
The e.preventDefault()
solution mentioned helps you to stop the trigger from being run, and then allows you to validate the form inputs before you actually trigger the event in Google Tag Manager.
The validation of inputs depend on what inputs are required in your form, so this will have to vary based on each form you create. But you could use a generic function that checks all inputs with class 'required', like so:
// Get all required inputs
var requiredFields = document.querySelectorAll('input.required');
// Create function to validate inputs
function validateInputs(callback){
// Set formstatus to valid
var formOkay = true;
// Check each field
requiredFields.forEach(i => {
// Check error state
if ((i.value == "") || ((i.type === 'checkbox') && (i.checked == false))) {
// Form was invalid
console.log('Form was invalid');
formOkay = false;
}
})
// Return formStatus;
callback(formOK ? true : false);
}
Now you can use this function to validate the form, before you send the Google Tag Manager trigger, like so:
document.getElementById('mc-embedded-subscribe-form').addEventListener('submit', e => {
e.preventDefault();
validateInputs( res => {
// check res
if (res == true){
dataLayer.push({'event':'formSubmit'});
}
})
})
Note: This solution will check that the form inputs are valid, and not if the user was actually subscribed to the list. The best approach would be to subscribe the user, using ajax and then trigger the GTM-tag if the callback returns with status success.
Solution 2:
I used a mutation observer to listen for changes to the div with the success message, which then could push an event to the dataLayer
// The element with success message
const successElement = document.getElementById('mce-success-response');
if(successElement){
const mutationConfig = { attributes: true };
const callback = function(mutationsList, observer) {
for(const mutation of mutationsList) {
if (mutation.type === 'attributes'
&& mutation.attributeName == 'style'
&& successElement.style.display === '') {
window.dataLayer.push({
"event" : "my-super-hot-lead"
})
}
}
};
const observer = new MutationObserver(callback);
observer.observe(successElement, mutationConfig);
}
Post a Comment for "Tracking Validated Submissions Using GTM On Mailchimp Embedded Form"