Reputation: 6295
I have a Google Analytics event being pushed each time a user clicks on a form submission button that enrolls the users in a course. The event is created using data attributes in the form button.
What's weird is that it seems to work only about half the time - the course has received twice as many enrollments as there are recorded events. Clicking on this button is the only way to enroll.
<form class="program-button register-course-form" action="/enroll-program/?course=personal-finance" method="post">
<input type="hidden" name="course_id" value="1850">
<button type="submit" class="btn btn-primary ga-click" data-ga-category="Academy" data-ga-action="Enroll" data-ga-label="Personal Finance">I agree</button>
</form>
jQuery(document).ready(function($){
// For elements with the .ga-click class, get information on the category,
// action, and label and report it to Google Analytics
$('.ga-click').click(function(){
var ga_category = $(this).data('ga-category');
var ga_action = $(this).data('ga-action');
var ga_label = $(this).data('ga-label');
ga('send', 'event', ga_category, ga_action, ga_label)
});
});
Upvotes: 2
Views: 324
Reputation: 9164
As pointed out by Niklas, you need to use a hit callback in this case. However, you also need to take into account that users may block Google Analytics using some privacy protection tool such as Ghostery, in which case the hit callback will never be executed. Therefore you need to implement this very carefully so that your site doesn't appear to be broken for these users. The same problem occurs when tracking outbound links using Google Analytics. The following article explains how to implement this properly:
http://veithen.github.io/2015/01/24/outbound-link-tracking.html
Upvotes: 0
Reputation: 30012
The analytics call is asynchronous and the way you have it setup does not guarantee that the analytics event has been succesfully sent by the time the form post is processed, which means it could get interrupted.
You'll need to block the form post until you know when the google analytics event has been succesfully sent. Here's some information on how to implement a hitCallback
:
https://developers.google.com/analytics/devguides/collection/analyticsjs/advanced#hitCallback
Upvotes: 2