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.

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



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

ga('send', 'pageview');


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'});

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