Reputation: 787
I searched a lot about this issue but I can't find anything good. I think that this is a common problem: you have a web app and build JSON APIs on top of your platform, so you can develop some widgets, mobile apps or third party applications.
I know that there a are a lot of specific analytics services via API (like Mixpanel, Kissmetrics and many others) but I want to track all the JSON calls also via Google Analytics.
I found that the best method is to use the __utm.gif image but strangely I cannot find any plugin or gem to use this image. So I tried to build my own method without success (see the code below)... Someone can help?
def google_analytics_call(page_title)
today = Time.now.to_i
utma = cookies[:__utma].to_s
utmb = cookies[:__utmb].to_s
utmc = cookies[:__utmc].to_s
utmz = cookies[:__utmz].to_s
utma = (rand(8).to_s + "." + rand(10).to_s + "." + today.to_s + "." + today.to_s+ "." + today.to_s) unless cookies[:__utma]
utmb = rand(8).to_s unless cookies[:__utmb]
utmc = rand(8).to_s unless cookies[:__utmc]
utmz = rand(8).to_s+ "." + today + ".2.2.utmccn%3D(direct)%7Cutmcsr%3D(direct)%7Cutmcmd%3D(none)" unless cookies[:__utmz]
Thread.new do
params = {
:utmac => GOOGLE_ANALYTICS,
:utmcc => "__utma%3D"+utma+"%3B%2B"+"__utmb%3D"+utmb+"%3B%2B"+"__utmc%3D"+utmc+"%3B%2B"+"__utmz%3D"+utmz+"%3B%2B",
:utmcn => "1",
:utmcs => "-",
:utmdt => page_title, #page title
:utmhn => BASE_URL,
:utmwv => 1,
:utmt => "page",
:utmr => request.referer
}
puts params
http_get("www.google-analytics.com", "/__utm.gif", params)
end
end
Upvotes: 8
Views: 2626
Reputation: 2069
i think you want to use the async tracker, which is part of google analytics. Here is an example of how I track clicks that fire an async AJAX event:
$('.trackable').bind('click', function(event){
var action = $(this).attr('action');
var category = $(this).attr('category');
_gaq.push(['_trackEvent', action, category]);
});
The "_gaq" is the google asynchronous queue and can be added to any JS function you want to track metrics within. The function above allows you to add a class called "trackable" and track events when the user clicks on it. An example looks like this:
<a category='FEATURED' action='Like This' class='trackable' href="http://MYSSERVER.com/foo.json" target='_blank'>track asynchronously.</a>
Upvotes: 3