Track jQuery AJAX Requests in Google Analytics

06 January 2011

There is an easy way to track all jQuery AJAX requests in an application. This method could really be used to log our AJAX requests however we wish, but this particular example will log requests to Google Analytics.

The code

This code will automatically log all jQuery AJAX requests in our application, including those using `$.ajax()`, `$.get()`, or `$.post()` (and `.load()` too).

This will also work for any jQuery plugins using AJAX requests (e.g. lightbox plugins, etc.), as well as for all Rails 3 remote links and forms (provided we're using the jQuery UJS driver).

In the page layout or in an included js file, we add the following JavaScript:

Updated to make sure _gaq is defined and loaded in page. Thanks to Bart Claeys below for pointing this out.

(function ($) {

  // Log all jQuery AJAX requests to Google Analytics
  $(document).ajaxSend(function(event, xhr, settings){ 
    if (typeof _gaq !== "undefined" && _gaq !== null) {
      _gaq.push(['_trackPageview', settings.url]);
    }
  });

})(jQuery);

If we're using this in a Rails 3 app, we can put this in our application.js.

Notes

This assumes we're using the Asynchronous version of Google Analytics. If we're using the older synchronous Analytics code snippet, we just need to replace the _gaq with the older pagetracker syntax:

(function ($) {

  // Log all jQuery AJAX requests to Google Analytics
  $(document).ajaxSend(function(event, xhr, settings){ 
    if (typeof pageTracker !== "undefined" && pageTracker !== null) {
      pageTracker._trackPageview(settings.url);
    }
  });

})(jQuery);

Also, notice we don't need to put the JavaScript inside the $(document).ready() event. This is because we're only binding a function to a callback, to be run later when the callback is triggered; we're not actually executing any code on the DOM yet.

How it works

jQuery fires off several local and global AJAX callbacks whenever it executes an AJAX request. The local callbacks fire on the specific element that triggered the AJAX request (i.e. the link or form), while the global callbacks are broadcast to all elements in the DOM, including the root node, document.

So, we're simply binding a function to the root node, on the ajaxSend callback. That function then uses the Google Analytics function for manually logging a page request for the AJAX URL.

On a related note, if we want to make a specific AJAX request stealthy, and not broadcast its global AJAX callbacks to other DOM elements, we can set global to false. This will also cause our Analytics tracking to be skipped for this request.

$.ajax({
  url: '/like-a-ninja',
  global: false
});

About the author:

Steve Schwartz // Owner of Alfa Jango Web-based Software, creator of RateMyStudentRental & LeadNuke, engineer, hacker, rubyist, guitarist, aspiring racecar driverist.



Comments are loading...