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
2
3
4
5
6
	(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-xxxxxxxx-x', 'xxxx.com');
	ga('send', 'pageview');

Becomes this:

1
2
3
4
5
6
7
8
9
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-XXXXXXXX-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);
  })();

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

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