How to set up form tracking analytics with Google Tag Manager and Google Analytics

173
3922
Downloads
959.24 Kb

The conversion rate is one of the simplest and at the same time most important measures of marketing efficiency. It shows how many users have completed a target action: made a purchase, signed up for emails, requested a call, etc. For recording and analyzing e-commerce sales, we have Google Analytics, which is relatively easy to configure. More effort is required, however, to track forms submitted on a site. 

That’s because forms happen to be of different types and use different technologies for sending data to the server. After data is successfully sent, some form fields are updated. Others show a pop-up window. A third type redirects the user to a thank you page. The method of form tracking depends on the technology that is used. 

In this article, we tell you how to collect form data in different ways and transfer it to Google Analytics. 

Method 1. Separate thank you page

If the user is redirected to a separate page with a different URL after completing the form, tracking visits to this URL is the easiest method to track form submission. It’s enough for you to create a target with the type “Landing Page” in Google Analytics. 

Let’s say you want to track registrations for a webinar. The thank you page after successfully registering looks like this: https://www.site.com/registration/thankyou

In the Admin panel, in View Settings, under Targets, click Target, then click Custom. Specify the target name, select the target type, and enter the address of the thank you page:  

Google Analytics admin panel

What’s important to consider: The URL of your thank you page should be unique – that is, there should be only one page on the site with such an address, and users should not be able to get to this page without filling out the form. Otherwise, Google Analytics can record inaccurate data about the achievement of your goal.

Method 2. Submit form trigger in Google Tag Manager

If your programmers correctly configured data transmission from a form by means of the submit button, then for form tracking submissions you can use the built-in Google Tag Manager trigger. Judging by comments on the Internet, this situation is encountered infrequently, but it’s worth trying.

Using this method, when a user fills in and sends a form, the trigger sends a gtm.formSubmit event to the dataLayer array.

Note: Before you go to settings, make sure the Page View tag is enabled in Google Tag Manager for all pages on the site. 

Step 1. Activate form variables

For this purpose, open the Variables menu in GTM, click Configure, and select all variables in the Forms section:

GTM menu

Step 2. Adjust the trigger

You need a form id or form class attribute to create a trigger. You can see them in the HTML code by right-clicking your form and clicking Explore Item in Firefox or View Code in Chrome: 

In our example, the form id is send-request-form, which we will use when configuring the trigger. 

Go to the Triggers menu, click New, open Trigger Settings, and select Submit Form

Choosing trigger type in Google Tag Manager

In the window that opens, you’ll see two checkboxes:

    • Wait for tags – If you enable this option, the form will not be sent until all tags associated with it are activated or the time you specify expires.

    • Check validation – It’s best to enable this option. Otherwise, the trigger will fire even when the user hasn’t filled in the required fields.

    After you activate error checking, additional settings appear. If you enable the trigger, specify the URL of the page that contains your form. And if you activate the trigger, specify the form ID that we mentioned above:

    Google Tag Manager

    Come up with a convenient and understandable name for the trigger, such as Submit a Request, and save it. 

    Step 3. Check whether the trigger works

    Before publishing changes in a container, use the preview mode in Google Tag Manager. Open the page with the form, fill it out, and hit send. In the debugging console, a gtm.formSubmit event should appear.


    Google Tags Manager menu

    If this event doesn’t appear, then this method of tracking won’t work for you. In that case, try one of the other methods described in this article. 

    If the event does appear, it’s still necessary to carry out one more test to check whether the trigger works correctly. Open a form, leave some obligatory field blank, and submit the form. If a gtm.formSubmit event appears in the debugging console again, then the built-in trigger works incorrectly and won’t help you. If the event wasn’t transferred, that’s great! Move to the next steps. 

    Step 4. Create the tag

    Now you need to create a tag that will send information to Google Analytics that the form has been sent. To do this, go to the Tags menu, click New, open Tag Configuration, and select Google Analytics – Universal Analytics.

    For clarity, you can name the tag the same as the trigger. Next, fill in the following fields: 

    • Tag Type – select {{Google Analytics Settings}}
    • Track Type – select “Event”
    • Category – the same as the tag and trigger for convenience
    • Action – Sending
    • Label – for example, {{Form ID}})
    • Non-Interaction – leave “False”

    If you want to activate the tag, select the trigger you created in Step 3 and click Save:  

    Tag configuration form in Google Tag Manager

    It’s ready! You can check how the generated tag works when submitting a form using the Google Tag Manager preview mode or using the real-time Events report in Google Analytics. 

    Step 5. Set up your target in Google Analytics

    Once you publish the container with changes, you need to set up the target in Google Analytics to consider submitting forms as conversions. To do this, add a new goal of your own in the Google Analytics view settings. Select the Event type and fill in the Category, Action, and Shortcut fields just as you did when you configured the tag in Google Tag Manager:

    admin panel in Google Analytics

    Save the target. Done. You’ve set up form tracking without changing any code on your site!

    Method 3. Element availability trigger in Google Tag Manager

    If a window pops up on the site with a thank you or a message about successful submission after sending a form, you can try another built-in GTM trigger. It fires when a particular item appears on the screen (in our case, a pop-up window) and dispatches a gtm.elementVisibility event to the dataLayer. 

    To configure this trigger, you must know the CSS selector of the monitored item. To find this selector, right-click the window and select View Code. You’re looking for the following line: 

    To copy the CSS selector, right-click the line and select Copy – Copy selector:

    How to copy selector

    In our example, the selector looks like this: #webinar_marketing_automation > div.

    Then create a new trigger by selecting the Element Visibility type:



    Fill out the following fields:

    • Trigger name – for example, “Get webinar recording”
    • Selection Method – CSS Selector
    • Element Selector – Insert the value you copied from the HTML code of the pop-up window.
    • Trigger rule – If you have one form on the page, leave the option “Once per page.” If there are multiple forms and one message pops up, you can select “Once per element.”
    Element selector in Google Tag Manager menu
    • Then check the box “Register DOM changes.”
    • Trigger Activation Conditions – By selecting “Some Visibility Events,” you can specify the page where the pop-up message or text appears.
    • Save the trigger.
    advanced options in Google Tag Manager menu

    After you create the Element Availability trigger, you must adjust the same settings as described in detail in Method 2:

    • Add a new tag to GTM that will send form submission data to Google Analytics and attach the created trigger to it.
    • Preview how the tag works when the form is submitted.
    • In Google Analytics, set the Event target to track conversions.

    Method 4. Track forms that use AJAX

    If forms on your website use AJAX technology, then data is transferred from the browser to the server in the background and the page doesn’t reload. To configure tracking of AJAX forms submitting, you can use this script from Lunametrics:

        
    <script id="gtm-jq-ajax-listen" type="text/javascript">
      (function() {
     
        'use strict'
    	var $;
        var n = 0;
        init();
     
        function init(n) {
     
          // Ensure jQuery is available before anything
          if (typeof jQuery !== 'undefined') {
    		
            // Define our $ shortcut locally
            $ = jQuery;
            bindToAjax();
     
          // Check for up to 10 seconds
          } else if (n < 20) {
    	
            n++;
            setTimeout(init, 500);
     
          }
     
        }
     
        function bindToAjax() {
     
          $(document).bind('ajaxComplete', function(evt, jqXhr, opts) {
     
            // Create a fake element for magically simple URL parsing
            var fullUrl = document.createElement('a');
            fullUrl.href = opts.url;
     
            // IE9+ strips the leading slash from a.pathname because who wants to get home on time on Friday anyways
            var pathname = fullUrl.pathname[0] === '/' ? fullUrl.pathname : '/' + fullUrl.pathname;
            // Manually remove the leading question mark, if there is one
            var queryString = fullUrl.search[0] === '?' ? fullUrl.search.slice(1) : fullUrl.search;
            // Turn params and headers into objects for easier reference
            var queryParameters = objMap(queryString, '&', '=', true);
            var headers = objMap(jqXhr.getAllResponseHeaders(), '\n', ':');
     
            // Blindly push to the dataLayer because this fires within GTM
            dataLayer.push({
              'event': 'ajaxComplete',
              'attributes': {
                // Return empty strings to prevent accidental inheritance of old data
                'type': opts.type || '',
                'url': fullUrl.href || '',
                'queryParameters': queryParameters,
                'pathname': pathname || '',
                'hostname': fullUrl.hostname || '',
                'protocol': fullUrl.protocol || '',
                'fragment': fullUrl.hash || '',
                'statusCode': jqXhr.status || '',
                'statusText': jqXhr.statusText || '',
                'headers': headers,
                'timestamp': evt.timeStamp || '',
                'contentType': opts.contentType || '',
                // Defer to jQuery's handling of the response
                'response': (jqXhr.responseJSON || jqXhr.responseXML || jqXhr.responseText || '')
              }
            });
     
          });
     
        }
     
        function objMap(data, delim, spl, decode) {
     
          var obj = {};
     
          // If one of our parameters is missing, return an empty object
          if (!data || !delim || !spl) {
     
            return {};
     
          }
     
          var arr = data.split(delim);
          var i;
     
          if (arr) {
     
            for (i = 0; i < arr.length; i++) {
     
              // If the decode flag is present, URL decode the set
              var item = decode ? decodeURIComponent(arr[i]) : arr[i];
              var pair = item.split(spl);
     
              var key = trim_(pair[0]);
              var value = trim_(pair[1]);
     
              if (key && value) {
     
                obj[key] = value;
     
              }
     
            }
     
          }
     
          return obj;
     
        }
     
        // Basic .trim() polyfill
        function trim_(str) {
     
          if (str) {
     
            return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
     
          }
     
        }
     
     
      })();
      /*
       * v0.1.0
       * Created by the Google Analytics consultants at http://lunametrics15.staging.wpengine.com
       * Written by @notdanwilkerson
       * Documentation: http://lunametrics15.staging.wpengine.com/blog/2015/08/27/ajax-event-listener-google-tag-manager/
       * Licensed under the Creative Commons 4.0 Attribution Public License
       */
    </script>
        
    

    This code checks whether your form really uses AJAX, then creates the variable and trigger in Google Tag Manager. 

    Step 1. Create a tag to check how your form works

    In Google Tag Manager, open Tags, click New, click Tag Configuration, then select Custom HTML. Copy the code above and paste it into the text box. Specify all pages as triggers: 

    Then turn on the GTM preview, open the form page, complete the form, and submit it. 


    Data Layer in Google Tag Manager

    If in the debugging console an ajaxComplete event appears (as in the screenshot above), then your form uses AJAX and this method of tracking suits you. In that case, read further.

    Step 2. Create a data layer variable

    If you click the ajaxComplete event in the preview console and then open the Data Layer tab, you’ll see what information is passed to the data tier array after the form is submitted. 

    We’re interested in the response line in this code; it contains text saying that the form was successfully submitted:



    This line can be used for creating the variable and trigger in Google Tag Manager. Open the Variables section in GTM, click Create, and on the Variable Configuration screen, select Data Layer Variable. In the Data Layer Variable Name field, write attributes.response (it’s possible to name two variables the same thing) and save the settings.

    Why enter attributes.response instead of response? Because attributes is an object that contains the response key and its value. By doing so, we point GTM to the exact path to the data that interests us.

    After creating a variable, it’s necessary to check it. For this purpose, submit a form in preview mode. Click on the ajaxComplete event and open the Variables tab in Google Tag Manager. If you see the attributes.response variable and the text about successfully sending the form, it means you’ve configured everything correctly.

    Step 3. Create the trigger

    In the Trigger Configuration section, click Create, then Trigger configuration and select the User event type. Specify ajaxComplete in the Event Name field. Then as the condition for activating the trigger, select Some Custom Events and register a condition: the attributes.response variable contains {enter your custom text about successfully sending the form}. 

    Trigger Configuration menu

    After that, what remains is: 

    • Adding a new Event tracking tag to GTM that will send form submission information to Google Analytics and attach the created trigger to it.
    • Using Preview mode to check how the tag works when submitting a form.
    • Setting the Event target to track conversions in Google Analytics.

    We’ve described these settings in detail above in the section Method 2. Send form trigger in Google Tag Manager.

    Method 5. DataLayer events as trigger

    Tracking forms using the dataLayer .push method is, in our view, the most reliable and versatile solution. The only drawback is that if you don’t understand the code, you’ll need the help of developers. 

    Prepare technical specifications for developers
    Make a list of the settings you want to transfer in the dataLayer after the form is successfully submitted. Ask your developers to add this code to all pages with forms you want to monitor:

    dataLayer.push({
    'event':'Forms', 'variable': 'value'     
    }) 

    Where:

    • Event is the name of an event. You can replace it with any event that’s convenient for you.
    • Variable is a set of all variables you want to transfer together with an event.

    After your programmers configure the dataLayer.push method for all forms, you can check how it works. For this purpose, include a preview in Google Tag Manager and fill out the form on your website. In the debugging console, there should be a new event (in our example, it’s called OWOX). When clicking on an event and going to the dataLayer tab, you’ll see all parameters that are transferred to the data array: 

    Google Tag Manager menu

    In the example of our event in the screenshot above (downloading a PDF file from the blog), we consider how to configure tracking with GTM.

    First, create all required user variables: eventCategory, eventAction, eventLabel, etc. Then select the Variable Type in User-Defined Variables section and enter a variable name in braces: {{eventCategory}}: 

    Next, create a trigger of the type Custom Event. In the settings, specify the event name and set the trigger to fire on All Custom Events: 

    Trigger Configuration menu in Google Tag Manager

    Then create a tag that will forward events to Google Analytics. Set the tag type as Google Analytics – Universal Analytics, and set the tracking type as Event. 

    Further, fill in these fields:

    • Category – {{eventCategory}}
    • Action – {{eventAction}}
    • Label – {{eventLabel}}

    Next, select a variable {{Google Analytics settings}} and the trigger you created in the previous step: 

    Google Tag Manager menu

    Everything is ready. All that remains is to check whether the tag works in GTM preview mode and in real-time Google Analytics reports. 

    How much time users spend filling out your forms

    Now that you can find out how many users have successfully completed the form, it will be helpful to find out what problems have been encountered by those who haven’t completed it.

    Your developers need to add to the dataLayer the names and values of all parameters required for form analytics. This will help you track: 

    • Time from page opening to field activation
    • Time from field activation to field deactivation
    • Time from activation of the first field to the first submission of the form
    • Time from activation of the first field to successful submission of the form
    • Time from activation of the first field to failed form submission
    • Time to get a response from the server about successfully submitting a form
    • Time to get a response from the server about unsuccessfully submitting a form
    • Time from form activation to when a user leaves the form (without successfully submitting it)

    Once you’ve set up a collection of this data in Google Analytics, you’ll be able to import that data into Google BigQuery – for example, using OWOX BI. Then you can build any form analytics reports in Google Sheets using the free OWOX BI BigQuery Reports Add-on. 

    These reports will help you find and fix problems in the usability of your forms and thus increase your conversion rate. 

    Here are some examples of such reports and the questions they can answer:

    1. When interacting with which form fields do users most often encounter an error?

    2. How long do users spend filling out the form?

    3. How much time do users spend filling out the form and what does it depend on? 

    P.S. If you need help setting up form analytics and creating a custom metrics system for your business, email us at contact@owox.com or fill out the contact form on the OWOX website.

    You might also like

      Trusted by

      Rozetka.ua

      Professional Team!

      We are grateful for the efficient cooperation with OWOX. Particularly I would like to acknowledge their active involvement during the implementation process and while configuring the analytics platform for our needs: setting up Google Tag Manager, enabling the latest Google Analytics functions for our account, integration with Google BigQuery. Now we can better understand customers acquisition, behaviour and ways to improve ROI and revenue with OWOX Business Intelligence tools.