Recording AJAX Requests with Google Analytics

Hey everyone,

I’ve just finished setting this up on an AJAX-heavy site I’m working on. It’s all pretty easy to setup, copy the following code and use it to replace your standard analytics code:

This:

  1. 	(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  2. 	(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  3. 	m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  4. 	})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
  5. 	ga('create', 'UA-xxxxxxxx-x', 'xxxx.com');
  6. 	ga('send', 'pageview');

Becomes this:

  1.   var _gaq = _gaq || [];
  2.   _gaq.push(['_setAccount', 'UA-XXXXXXXX-X']);
  3.   _gaq.push(['_trackPageview']);
  4.  
  5.   (function() {
  6.     var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
  7.     ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
  8.     var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  9.   })();

And the last step is to add this JavaScript whereever your ajax request is being made, for instance: _gaq.push([‘_trackPageview’, ‘/contents/get_content_by_id/’ + id]);

  1.         //Prepare ajax
  2. 	$.ajax({
  3. 		mtehod: 'GET',
  4. 		url: '/contents/get_content_by_id/' + id,
  5. 		dataType: 'JSON',
  6. 		success: function(data){
  7.  
  8. 			//Handle response
  9. 			handle_ajax_response(data);
  10.  
  11. 			//Push view to analytics
  12. 			_gaq.push(['_trackPageview', '/contents/get_content_by_id/' + id]);
  13. 		},
  14. 		error: function(){
  15.  
  16. 			//Remove loader and display error
  17. 			remove_loader(target_selector, null);
  18. 		}
  19. 	})

Just add the line commented Push view to analytics and you’re done. To test it, I just used to the real-time analytics – it shows up straight away. If you run into any trouble the docs are pretty decent: https://developers.google.com/analytics/devguides/collection/gajs/

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.