Google Analytics tracker in an ajax application

google-analytics-+-ajax-navigation

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 http://support.google.com/googleanalytics/bin/answer.py?hl=en&answer=55488 )

var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' 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 ) {
    try{
        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.

5 Comments

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>