Reputation: 125
I've been trying to set up code to track downloads of files on a website. I just updated the code from the original tracking snippet to the asynchronous code, ga.js, (in the local.php5 file to track all pages on the site) but I don't know what code to use to track downloads on one certain page.
I found this code but I don't know if it is correct; it hasn't been showing any events when I check GA.
<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);
})();
$(document).ready(function(){
$('.dl-tracking').on('click', function (){
_gaq.push(['_trackEvent', 'download']);
});
});
</script>
the certain links are outputted using a for-each loop in PHP so I tried putting this code in to work
$variable .= "<a href='$name/media/Material/$x->path' target='_blank onClick="_gaq.push(['_trackEvent', 'TM', 'Download',]);">$fileName</a>";
but I got a T_STRING error for that line. I'm a bit new to PHP so I don't know where my errors are.
Upvotes: 1
Views: 418
Reputation: 862
When tracking Events in Analytics (whether ga.js or the newer analytics.js), the Event Category and Event Action are required (see the official documentation):
category (required): The name you supply for the group of objects you want to track.
action (required): A string that is uniquely paired with each category, and commonly used to define the type of user interaction for the web object.
label (optional): An optional string to provide additional dimensions to the event data.
value (optional): An integer that you can use to provide numerical data about the user event.
non-interaction (optional): A boolean that when set to true, indicates that the event hit will not be used in bounce-rate calculation.
You should thus have something similar to:
jQuery(document).ready(function ($) {
$('.dl-tracking').on('click', function () {
// You might want to also add the link text/href here:
_gaq.push(['_trackEvent', 'Download', 'Click']);
});
});
As for your PHP exception, it happens because your quote and double-quote characters (' and ") should be escaped in the following line of code:
$variable .= "<a href='$name/media/Material/$x->path' target='_blank onClick="_gaq.push(['_trackEvent', 'TM', 'Download',]);">$fileName</a>";
It should be corrected to something similar to:
$variable .= '<a href="'.$name.'/media/Material/'.($x->path).'" target="_blank" onClick="_gaq.push([\'_trackEvent\', \'TM\', \'Download\']);">'.$fileName.'</a>';
Upvotes: 1