Track event in google analytics upon clicking form submit

Use Google Analytics hitCallback

You can specify a custom callback function on the tracker object.

_gaq.push(['_set', 'hitCallback', function(){}]);

The callback is invoked after the “hit is sent successfully.”

If you want to track a click on a submit button and send the form afterwards you can use the following code (uses jQuery) for your event:

var _this = this; // The form input element that was just clicked
_gaq.push(['_set','hitCallback',function() {
    $(_this).parents('form').first().submit(); // Submit underlying form
}]);
_gaq.push(['_trackEvent', 'My category', 'My action']);
return !window._gat; // Ensure that the event is bubbled if GA is not loaded

Or as onclickone liner for your <input type="submit"> element:

onclick="var _this=this;_gaq.push(['_set','hitCallback',function(){$(_this).parents('form').first().submit();}]);_gaq.push(['_trackEvent','My category','My action']);return !window._gat;"

What it does it that it tracks the event My category/My action, uses jQuery to find the underlying form element of the submit button just pushed, and then submits the whole form.

See: Google Analytics – Sending Data to Google Analytics – Hit Callback (thanks supervacuo)

UPDATE
If you’re using modern analytics.js code with ga() function defined, you can write this as following:

var _this = this;
ga('send', 'event', 'My category', 'My action', {
    'hitCallback': function() {
        $(_this).parents('form').first().submit();
    }
});

return !window.ga;

Leave a Comment