Google Analytics tracker in an ajax application


In this short post you are going to understand how to use the google analytics tracker to detect all the events that could be triggered in an ajax application. On the net there are many sources about that but I didn’t find any clear tutorial that shows how it could be easy to implement the google tracker and how to know if everything is working well.

First you should inject the google script inside your page ( source )

var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "' type='text/javascript'%3E%3C/script%3E"));

Then you are able to track all the events simply creating a callback function that thanks to the analytics tracker it can push new datas to the google servers:

function trackEvent ( data ) {
        var pageTracker = _gat._getTracker("UA-xxxxxx-x"); // don't forget to change this using your ID
        pageTracker._trackPageview( data );
    } catch(err) {}
trackEvent ( 'page/you/want/track' );

Now you could push every event calling the trackEvent function and passing a string that should represent your event or your page.
To check if your code is working you can use ‘Real Time ( Beta )’ that is a new feature you could find in your Analytics admin page.

If your code is catching the events you should watch them in the real time report.

That’s it, enjoy the code.


Leave a Reply

Your email address will not be published. Required fields are marked *