Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firing a google analytics event on form submit

I'm trying to add analytics event tracking to an onclick event for a submit input on a form.

I've tried multiple different examples and referenced a couple of different SO posts to get to this point. I'm able to get the onclick to either submit the form OR fire the tracking event but not both.

First example: (Submits form + logs to console but doesn't fire event)

<!-- Analytics tracking code -->

<form action="test.php" id="form" method="post">

    <input type="text" name="name" id="name">

    <!-- Submits form + logs to console but doesn't fire event -->

    <input type="submit" name="submit" value="Submit" onclick="
        var _this = this; 
        _gaq.push(
            ['_trackEvent', 'Forms', 'Submit', 'Home Contact'], 
            function() {
                console.log('submitting'); 
                $(_this).parents('form').submit();
            }
        );
    ">

</form>

Second example: (Fires event + logs to console but doesn't submit form)

<!-- Analytics tracking code -->

<form action="test.php" id="form" method="post">

    <input type="text" name="name" id="name">

    <!-- Fires event + logs to console but doesn't submit form -->

    <input type="submit" name="submit" value="Submit" onclick="
        var _this = this;
        _gaq.push(['_set','hitCallback',function(){
            console.log('submitting');
            $(_this).parents('form').submit();
        }]);
        _gaq.push(
            ['_trackEvent','My category','My action']
        );
        return !window._gaq;
    ">

</form>

I've also found that if I add return false to the end of the first example's onclick event it will fire the analytics event tracking but not submit the form.

like image 726
James Avatar asked Oct 21 '13 15:10

James


1 Answers

(This really needs to be a FAQ...)

Google Analytics records data by requesting an image from the analytics servers, with the tracking data as parameters on the image request. If a new page is rendered in the current window immediately after a _trackEvent or _pageView, the image request can be canceled, and no data recorded.

The usual pattern is to add a small delay before loading a new page or submitting a form.

Try

<input type="submit" name="submit" value="Submit" onclick="
  var _this = this; 
  _gaq.push(['_trackEvent', 'Forms', 'Submit', 'Home Contact']);
  setTimeout(function() {$(_this).parents('form').submit()}, 150);
  return false;"
>

My preference is bind to the jQuery submit event on the form itself, like

$('#form').submit(function(e){
  e.preventDefault();
  _gaq.push(['_trackEvent', 'Forms', 'Submit', 'Home Contact']);
  var form = this;
  setTimeout(function(){ form.submit()}, 150);
});
like image 167
mike Avatar answered Oct 16 '22 10:10

mike