Recommended:

  • phpclasses.org
  • jsclasses.org
  • jsmag.com
  • siteapps.com
  • View our reviews on Hot Scripts
  • JS Tutorial
  • scripts.com
  • securesignup.com




Recent Comments

Powered by Disqus




Back to articles

Collecting Feedback Using Google Analytics Events and Custom Variables

Google Analytics is a powerful tool that generates detailed statistics about your website’s traffic, but its options are not limited to only tracking visitors. It is also capable of tracking visitor’s interaction with website and even providing an option for a feedback, using events and custom variables.

Sponsored by 

This article was written and published in JSMag August issue.

If you have an idea and want to write articles about Web development, Javascript or Groovy, submit your ideas to WebDevPub.com and get paid for your articles.

There are many reasons to create a website. But it doesn’t matter if you create a website to share information, sell your product/service, or just meet new people; in the end all that matters is traffic. Google Analytics is a great way to analyze it: you can determine which pages are most popular by examining average time visitor spends on each page, or plan your advertising budget using only the best traffic sources, which provide visitors with a higher page view per visit rate. But do you know, for example, how many times a user filled out a registration form, but hesitated to press submit and for whatever reason just left the page without registration? Google Analytics provides tools to track even these kinds of actions; all you need is some programming knowledge and a lot of imagination.

First let’s look at how Google Analytics actually works. There are two ways you can implement Google Analytics: asynchronous tracking and traditional tracking. Asynchronous tracking is the recommended way of using Google Analytics and an example is shown in Listing 1.

<script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-XXXXX-X']);
    _gaq.push(['_trackPageview']);

    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; 
		ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') +
		 '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; 
        s.parentNode.insertBefore(ga, s);
    })();
</script> 

Listing 1: Google Analytics Asynchronous tracking implementation

The main difference between asynchronous and traditional tracking is that first one doesn’t delay load of other web content. It creates a queue array before the Analytics script is loaded: var _gaq = _gaq || []. Then it is possible to add Analytic’s commands to the queue using the _gaq.push() method, for example, set your account ID : _gaq.push(['_setAccount', 'UA-XXXXX-X']) (replacing X’s with your account ID) or send tracking data to the Google Analytics servers : _gaq.push(['_trackPageview']). After that Analytics script is dynamically added to the DOM tree and then loaded asynchronously using the “async” attribute: ga.async = true. And when script is finished loading, it executes all commands stored in queue array.

Setting up an event

Event tracking is used to record user interaction with website’s elements. For example, if you have a player in your website with your videos or audio files, you may want to track how many times your visitors pressed the play button. Or how many visitors put the cursor into one of the inputs of your registration form, how many of them actually wrote something into it and then compare that to how many visitors actually submitted that form. The potential of event tracking is limitless; its amount however is not.

Caution: There is a limit of approximately 500 combined Google Analytics requests (both events and page views) that can be tracked for a single user session.

An example of Event tracking is shown in Listing 2. Events can be categorized and each category might have different actions. For example, two categories of events would be “Player” – which would hold player actions like “Play” or “Stop”, and  “Registration form”, which would contain actions like “Input focused”, “Input filled” and ”Form submitted”.

Categories and actions must be provided for each event, but there are also two optional parameters: string value, which can categorize actions as labels, and integer value, which will only appear in columns describing total and average values based on each event count. For example, you can add the name of the current song to the “Player” category actions as string values and provide the time of songs played together with the “Stop” action, to see which songs visitors listen to longer, and which are usually interrupted.

//asynchronous tracking
_gaq.push(['_trackEvent', 'category', 'action', 'string', 'integer']);
//traditional tracking
_trackEvent('category', 'action', 'string', 'integer'); 

Listing 2: Setting up Event tracking

Using Event tracking might decrease your bounce rate, because by Analytics definition bounce is a session with single interaction request, which by default is a page tracking request. And by performing an Event, another interaction request will be sent and the current session won’t be interpreted as bounced even if a visitor leaves page. So actually using Event tracking might provide you with more accurate Bounce rate information than the standard Google Analytics implementation.

Warning: Using Event tracking on page load, when, for example, tracking page loading time, will result in 0% Bounce rate in your Google Analytics reports.

          Setting custom variables

Google Analytics provides a way to bind a custom value to a visitor with a certain lifespan, but it is limited to only five slots for custom variables per visitor. That’s why you should consider using events over custom variables if possible. Try to use custom variables only if it is needed to track a visitor for certain period of time.

Most popular reasons for setting custom variables are: for tracking visitor session (for example, to check if a user is logged in, just set a custom variable on the login action) or for marking visitors (for example, if a user has invoked an event, you might want to mark him to ignore the same events from the same visitor). An example of setting a value on a custom variable is shown in Listing 3.

//asynchronous tracking
_gaq.push(['_setCustomVar', 'index', 'name', 'value', 'scope']);
_gaq.push(['_trackPageview']);
//traditional tracking
tracker._setCustomVar('index', 'name', 'value', 'scope');
tracker._trackPageview(); 

Listing 3: Setting a value on a custom variable

To set custom variables there are three parameters that are required. The first one is index, it can be in range from 1 to 5 and it reflects the sequence number of the slot - as I mentioned before, there are only 5 of them. Slot value will be required to get value back using the _getVisitorCustomVar(index) method. The second parameter is the name of the custom variable. The only purpose of this parameter is to categorize variable values from different visitors in your Google Analytics reports. The third parameter is the value of the variable that you want to save.

The last parameter is optional. It represents a scope of the variable and it determines its lifespan. There are three possible values for this parameter: 1, 2 or 3. Value 1 represents visitor level, where a variable value could be retrieved even if visitor leaves website and comes back after period of time less than 2 years. Value 2 represents session level, where a variable value could be retrieved for the period of time during which the visitor is active on the site. Value 3 represents page level and it is the default value if another scope parameter isn’t provided. Page level variables are saved until the next interaction request – page or event. It raises a question: why should page level variables be used, if instead it is possible to use events? The answer is simple, because events appear on different section of Google Analytics report. If you want to save a value similar to an event, but this value is tied to a visitor’s session, you should use a page level variable, so they both could be analyzed on the same report, for example, if you want to track activities of a logged in user, which pages did he or she visited, etc.

Things to be aware of before using custom variables:

  • Don’t use same variable names across multiple slots
  • Don’t mix different variable scopes in one slot. Scopes with lower value will not be overwritten by higher ones. Use _deleteCustomVar(index) method before saving variables in used slots.
  • The five slots are meant for all scopes, you can’t have 5 visitor and 5 session custom variables set simultaneously
  • The total combined length of any custom variable name and value may not exceed 64 bytes
  • The _setCustomVar method doesn’t send an interaction request by itself. You must invoke page tracking or event tracking request after using _setCustomVar to properly save value.
  • Even if the variable was deleted, it will still appear in your Google Analytics reports. Variable lifespan only affects for how long it would be possible to retrieve it’s value.

          Getting value from custom variables

Although usage of the asynchronous implementation is recommended, there are situations when traditional tracking is the only option. The main reason for using traditional tracking, is when you want to get a value from a tracking object’s methods, for example, getting the value of a custom variable. This problem exists due to usage of a queue array. We have no control of where and when our command will be executed, so there is no way to get the value returned by the command function. And all that the push method returns is a number of elements in an array, or in this situation the number of unexecuted Google Analytics commands.

But that doesn’t mean we should completely switch to the traditional implementation. It is possible to combine both of implementations by wrapping traditional code into functions and passing those to the  asynchronous queue array, like shown in Listing 4. This way we still maintain the advantage of asynchronous tracking and use the additional capabilities of the traditional implementation.

_gaq.push(function() {
var tracker = _gat._getTrackerByName();
    var custom_val = tracker._getVisitorCustomVar(1);
    if(typeof custom_val == "undefined")
    {
        alert("Value doesn't exist");
    }
    else
    {
        alert("Your value is: " + custom_val);
    }
});

Listing 4: Getting a value from a custom variable

So, in Listing 4, we get the traditional tracking object using the _gat._getTrackerByName() method. It is possible to specify the name of the tracking object, if you are using more than one, otherwise without passing name the default tracking object will be returned. If you’re not sure, you can always check if it’s the same object you set up for your page by checking the account ID using the _gat._getAccount() method, which should return same value you set in original tracking snippet:  _gaq.push(['_setAccount', 'UA-XXXXX-X']).

When the tracking object is retrieved, it is possible to get the value of a custom variable by simply providing the slot index (value from 1 to 5) that was used to save the custom variable to the tracker._getVisitorCustomVar(index) method. It will return the saved value or undefined if unable to retrieve value, thus making it easy to check and react accordingly.

          Collecting user feedback

Figure 1: Form for collecting user feedback

So now let’s create a simple application, which will allow visitors to rate our website from 1 to 5 using radio buttons and leave optional comments in text area like shown in Figure 1. For that we’ll use the code shown in Listing 5.

<html>
<head>
<script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-XXXXXXX-X']);
    _gaq.push(['_trackPageview']);

    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; 
		ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') +
		 '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; 
        s.parentNode.insertBefore(ga, s);
    })();
</script>
</head>
<body>
<div id='feedback_form'>
    <p id='notify'></p>
    <p><a href='#' onclick='close_form()'>Close form</a></p>
    <div id='feedback_rating'>
        Rating:&nbsp;
        <input type="radio" name="rating" value="1">1&nbsp;
        <input type="radio" name="rating" value="2">2&nbsp;
        <input type="radio" name="rating" value="3">3&nbsp;
        <input type="radio" name="rating" value="4">4&nbsp;
        <input type="radio" name="rating" value="5" checked>5&nbsp;
    </div>
    <p>Comment:</p>
    <p><textarea name='comment' id='feedback_comment' rows='3' cols='25'></textarea></p>
    <p><input type='button' value='Submit' onclick='get_feedback()'/></p>
</div>
<script type="text/javascript">
var close_form = function(){
    var form = document.getElementById("feedback_form");
    //hiding form
    form.style.display = "none";
    //we can combine variable and event in one function
    _gaq.push(function() {
        var tracker = _gat._getTrackerByName();
        //setting custom variable to visitor level
        //so we won't bother this visitor again
        tracker._setCustomVar(1, 'Feedback', 'Closed', 1);
        //and setting closed event
        tracker._trackEvent('Feedback', "Closed");
    });
};
var get_feedback = function(){
    _gaq.push(function() {
        var notify = document.getElementById("notify");
        var tracker = _gat._getTrackerByName();
        //check if visitor is already marked
        var val = tracker._getVisitorCustomVar(1);
        if(typeof val == "undefined")
        {
            //this visitor didn't submit feedback
            //nor closed the feedback form
            
            //find rating
            var radios = document.getElementById("feedback_rating").childNodes;
            var rating;
            for(var i = 0; i < radios.length; i++)
            {
                if(radios[i].checked)
                {
                    rating = radios[i].value;
                    break;
                }
            }
            
            //set up custom variable with rating
            tracker._setCustomVar(1, 'Feedback', rating, 1);
            
            //invoke rating event
            tracker._trackEvent('Feedback', "Rating", rating);
            //check for comment
            var comment = document.getElementById("feedback_comment");
            if(comment.value.length > 0)
            {
                //user left a comment
                //invoke comment event
                tracker._trackEvent('Feedback', "Comment", comment.value);
            }
            
            
            notify.innerHTML = "Thank you for your feedback";
        }
        else
        {   
            notify.innerHTML = "You've already submitted feedback or closed feedback form";
        }
    });
};
</script>
</body>
</html>

Listing 5: Simple feedback application

We will set our events in the “Feedback” category where we’ll have three different actions: “Rating” for the provided rating, “Comment” –for the provided comment and “Closed”  if the visitor just closed the form without submitting any feedback. We will mark the visitor using a visitor level custom variable if he or she closes the form, providing the value “Closed”. If the visitor submits feedback, we’ll check if this visitor already submitted feedback or simply closed the form. If not we’ll submit a Rating event with the rating value and check if there is any text in comment input and submit that as well. After that we’ll mark the visitor in the same way as we’d mark it if he or she closes the feedback form, only now we will provide the rating as a variable value.

Note: Events and Custom Variables don’t appear in Google Analytics reports the moment they were submitted. Allow up to 24 hours for Events and Custom Variables to show in your reports.

And here’s how it will look in our Google Analytics reports.  Figure 2 displays action values for the “Feedback” category. Then in Figure 3, you’ll see labels for action “Rating”. And Figure 4 displays custom variables that were set up to mark visitors.

Figure 2: Event actions for “Feedback” category

Figure 3: Labels for “Rating” action

Figure 4: Saved custom variables

Check out the more advanced feedback application “Feedback Easy”.


You may also be interested in:

Powered by BlogAlike.com

blog comments powered by Disqus