Tracking form submit events with Google Universal Analytics

Questionform.com payment pages are hosted in Paypal and Fastspring, and I’ve been using Google Analytics events to track outbound links to both payment providers. The purpose was to get an idea of the drop-out rates for each provider.

After a few weeks, I noticed the data coming in didn’t seem correct, Google Analytics was missing a huge percentage of submit actions. It turns out, my tracking code was incorrect:

$("form").on('submit', function() {
  if (_gaq)
    _gaq.push(['_trackEvent', 'my category', 'my action']);

  return true;
});

There is not enough time for analytics to send the data to the backend server, the browser will navigate away from the page before the event is registered.

To fix this, you will first need to upgrade to Universal Analytics, the new and improved version of Google analytics.

One of the new features of Universal Analytics is the ability to have a callback method executed after you’ve sent some data. This is perfectly suited to when you need to track an outbound link as an event, hitCallback is your friend:

var href = "http://www.domain.com";
ga('send', 'event', {
  'eventCategory' : 'myCategory',
  'eventAction' : 'myAction',
  'eventLabel' : 'myLabel',
  'eventValue' : 'myValue',
  'hitCallback' : function () {
    document.location = href;
  }
});