jqueryajaxgoogle-analyticsjquery-address

Using Google Analytics to track AJAX requests


I'm changing a big section of a website to use jQuery Address' deep linking AJAX features. I'm using URIs like mysite.com/#!/page1/subpage/ and so on.

I've read a good bit about tracking traffic with the _gaq.push() function, but I was wondering if it was possible to do it in a bit more traditional fashion...

Each AJAX request calls a PHP function that builds a page and returns it in an <HTML> wrapper, which lets me easily define custom page titles and so on.

If I put the analytics code on that page, will jQuery calling that page trigger it to track the visit?


Solution

  • Well you can use jQuery's AJAX Events to globally listen for AJAX requests and then push an index onto the _gaq array (this seems like the most maintainable approach):

    $(document).on('ajaxComplete', function (event, request, settings) {
        _gaq.push(['_trackPageview', settings.url]);
    });
    

    Note that .on() is new in jQuery 1.7 and is the same as .bind() in this case.

    Also note that I have not tested the contents of the arguments passed for global AJAX events.

    UPDATE

    You can also use $.globalEval() to parse scripts loaded in an AJAX response body: http://api.jquery.com/jquery.globalEval/

    success: function(data) {
    
        var dom = $(data);
    
        dom.filter('script').each(function(){
            $.globalEval(this.text || this.textContent || this.innerHTML || '');
        });
    
        $('#mydiv').html(dom.find('#something').html());
    
    }
    

    Source: jQuery - script tags in the HTML are parsed out by jQuery and not executed