简体   繁体   中英

How to push a form submission to the dataLayer in google tag manager (gtm)

More than a question, I want to give back to the community...

Here is a little snippet for a code that will help you guys push the submission of forms to the dataLayer in Google Tag Manager.

I noticed that there were explanations of how to push to the dataLayer, but there were no actual examples. So here it is. I'd recommend narrowing down the querySelector if you have more than 1 form on the same page, but even with that, it will help.

If anyone of you pros wanna suggest anything that'd work better so that people can see this thread just comment below:)

`

<script>
var inputs = [];
var inputs = document.querySelectorAll('input');
var dictionary = {};
  
var x = inputs.forEach(function(field) { 
  var key = field.getAttribute("name");
  var value = field.value;
  dictionary[key] = value;
});

window.dataLayer = window.dataLayer || []; 
  dataLayer.push({
  'event': 'formInfoPush',
  'ObjInfo': dictionary});
</script>

`

Many issues with that code.

  1. You declare globals. You don't need globals. Contain your code in a closure or have a functional approach.
  2. You're grabbing inputs only. Input is not the only field you can have. And the value is not always in the value of the field.
  3. You're passing field values to GTM. It's extremely rare that form fields content is needed for analytics since it can easily affect users' privacy. It's never a good idea to just shove all fields into the DL. In fact, it's pretty lazy and this attitude eventually leads to excessively heavy dataLayer with tons of useless information.
  4. You're lacking the trigger. This code won't do anything useful as it is. It should be contained in a function to be used as the form event callback.
  5. While the way you store stuff in an object is very convenient for you, it's going to be quite unpleasant to work with in GTM.

Finally, the real issue people have with form tracking is the trigger. Not grabbing content of the fields. And it's a good practice to push the form identifier to the dataLayer on the submission/attempt/error events instead of all the fields.

You're attempting to make a universal solution to a way-too-general problem. As a result, you don't really achieve much.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM