Thursday, May 21, 2015

Google Analytics to track AJAX requests

Recently I have faced one problem based on Google analytics.
  • We were displaying slide show with node navigation.
  • Means, for each next/prev click, we were displaying different page view. 
  • Each page view contains, its own node(page) URL & title.
  • Implemented below google analytics code to track each hits.
  • But problem is, on ajax success or at next / prev click, we could not able to send new node details to google analytics.
  • I have fixed that solution using below code.
1) Code will be available on each page reload.

I have placed below code at "html.tpl.php" , so that for each and every page load, it will send page details like node URL & title to google analytics.
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){

(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),

m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)

})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-56232568-1', 'auto');

ga('send', 'pageview');

</script>


2) Code for ajax success.

Use below code on ajax success or next/ prev slide success. So that on every ajax hit success, it will trigger page details based on below settings.
ga('send', 'pageview', {'page': 'send/your/site/url', 'title': 'some-page-tile-ajax-success'});

Note:
1. You should have valid google analytics account to get above script.
2. After creating your account, add your site.
3. It will take at least 24 hrs(Not exactly) to track your site. Don't expect immediate track after adding site.

No comments:

Post a Comment