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:


	(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
	ga('create', 'UA-xxxxxxxx-x', '');
	ga('send', 'pageview');		

Becomes this:

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-XXXXXXXX-X']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '';
    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]);

        //Prepare ajax
		mtehod: 'GET',
		url: '/contents/get_content_by_id/' + id,
		dataType: 'JSON',
		success: function(data){

			//Handle response

			//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:



, ,



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at

%d bloggers like this: