20

I am calling a page on my website using AJAX but for some reason Google Analytics is not registering the page visit. Do I have to do something to force it to register AJAX triggered pages?

I am using the latest Universal anaytics code as follows:

<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-XXXXXXXX-1', 'mywebsite.ext');
  ga('send', 'pageview');

</script>

I am using a JQuery AJAX call to the page containing the above snippet as follows:

<script>
//<![CDATA[             
$(document).ready(function(){

        $.ajax({
                url : "http://www.mywebsite.ext",
                type: "GET",
                async: false,
                data : { fromajax : "y" },
                success: function(data, textStatus, jqXHR)
                {
                        // alert("success - Data: " + data + "\ntextStatus: " + textStatus);
                },
                error: function (jqXHR, textStatus, errorThrown)
                {
                        alert("error \ntextStatus: " + textStatus + "\nerrorThrown: " + errorThrown + "\njqXHR: " + jqXHR);
                }
        });

});
//]]>

I am certain the page is being called as I have some logging statements writing to a database. I also know the Analytics code is working as I am testing it using the real time overview.

So to summarise, I have a page calling http://www.mywebsite.ext using AJAX and the destination page (http://www.mywebsite.ext) contains some Universal Analytics code which does not appear to track the page. If you visit the page normally from your browser the page is tracked fine.

I have since discovered from the thread that I can call the "ga" function with a virtual folder. I have therefore done away with the AJAX call and instead modified the Universal Analytics as follows:

<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-XXXXXXXX-1', 'mywebsite.ext');
ga('send', 'pageview', '/localfolder/page');
ga('send', 'pageview');

</script>

The problem I have now is that it calls ga('send', 'pageview', '/localfolder/page'); but not ga('send', 'pageview');

But I understand there is a minimum interval between events: Google Analytics Event Tracking - Minimal Interval between the events

I therefore added a setTimeout(function(){},2000); between events and the last event is still not called. I even went up to 9 seconds.

Community
  • 1
  • 1
user2599927
  • 201
  • 1
  • 3
  • 7
  • From what I can remember, you need to create a custom event in GA, and push the event to GA's message queue in your ajax call. – Fabricator Jun 13 '14 at 06:34

5 Answers5

22

The old standard for loading Google Analytics was the asynchronous method:

var _gaq=[["_setAccount","UA-#######-#"],["_trackPageview"]];
(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];g.async=1;
g.src=("https:"==location.protocol?"//ssl":"//www")+".google-analytics.com/ga.js";
s.parentNode.insertBefore(g,s)}(document,"script"));

That bit tracks the initial page load but not subsequent AJAX calls. Any time you want to track a page load, place add the following snippet:

// "_trackEvent" is the pageview event, 
_gaq.push(['_trackPageview', '/some-page']);

_trackPageview is used again but this time we provide the URL of the AJAX address that was loaded. Using the small JavaScript snippet above allows you to keep track of pageviews just as you would if the entire page reloaded. I'd recommend using this snippet with MooTools' History plugin.

Combined with Ajax, your code should be similiar to this:

jQuery(document).ajaxComplete(function(e, xhr, settings){
  var d = document.location.pathname + document.location.search + document.location.hash;
  _gaq.push(['_trackPageview', d]);
});

If you want to use the Universal Analytics Code, the syntax for virtual pageloads is different.

This is the syntax for tracking virtual pageviews in UA:

ga(‘send’, ‘pageview’, ‘path to your virtual page’);

Examples:

<a href=”http://www.example.com/gu/dw/seo-beginners-guide.pdf” onClick=”ga(‘send’, ‘pageview’, ‘/virtual/guides/download/seo-beginners-guide.pdf’);”> Download SEO Beginners Guide</a> 

So when a user clicks on the link ‘Download SEO Beginners Guide’, UA will generate a virtual pageview called ‘/virtual/guides/download/seo-beginners-guide.pdf’.

Sources:
http://davidwalsh.name/ajax-analytics
https://stackoverflow.com/a/7762559/3582159
http://www.optimizesmart.com/event-tracking-guide-google-analytics-simplified-version/

Community
  • 1
  • 1
GlabbichRulz
  • 948
  • 9
  • 28
  • Thanks GlabbichRulz. I am trying to follow your solution and since I am using Universal Analytics Code I looked at your syntax here: ga(‘send’, ‘event’, ‘’event category ‘, ‘event action’, ‘event label’, event value, {‘nonInteraction’: 1}); Am I supposed to add this within the Universal Analytics snippet after: ga('send', 'pageview'); And if so what do I put for the event category and action as all I want is to track the entire page. – user2599927 Jun 13 '14 at 07:04
  • you have to add it to the `$(document).ready()` function, directly after or before the `$.ajax({});` function. You can also call it in the success function if you only want to track successfull page loads. – GlabbichRulz Jun 13 '14 at 07:10
  • OK thanks for clarifying this. However looking at the syntax, how will it know to track the URL in the AJAX call? The parameters do not indicate this. Also do I not need to declare something for "ga" to be recognised? – user2599927 Jun 13 '14 at 08:04
  • Sorry for the confusing, i did not really answered your question with my answer i think.. I updated it now, i think it should be much clearer now :) – GlabbichRulz Jun 13 '14 at 08:25
  • OK thanks, so from what you are saying I need to call ga(‘send’, ‘pageview’, ‘path to your virtual page’);. If this one function tracks the page view then am I right in assuming that I don't actually need to make the AJAX call? Also I am sure if I called this function the "ga" will not be recognised. How do I ensure it is recognised, do I need to make another declaration? – user2599927 Jun 13 '14 at 08:36
  • I have updated my question to implement what you have suggested. The issue now appears to me that I cannot send too many events too close together. I have added a timeout between events but to no avail. – user2599927 Jun 13 '14 at 12:12
  • is your ajax code located above the analytics code? If this is the case, the ga() function is not defined yet. It is defined in the analytics code. – GlabbichRulz Jun 13 '14 at 17:03
  • hm, i am not sure if this is what you need, but according to this [site](https://developers.google.com/analytics/devguides/collection/analyticsjs/pages), you can also use this code, maybe it works: `ga('send', { 'hitType': 'pageview', 'page': '/my-overridden-page?id=1', 'title': 'my overridden page' });` But i think that this may be another problem or question, as the main problem, the tracking of virtual pages, is theoretically solved. Or, as another idea, does it work if you call `ga('send', 'pageview', '/localfolder/page');` after `ga('send', 'pageview');`? – GlabbichRulz Jun 13 '14 at 17:12
  • Just to let you know that the ga function is defined and working but I will try your other solutions. If I can't get it to work I will create a separate thread to deal with this speciifc issue. – user2599927 Jun 14 '14 at 09:47
3

This answer is for new GA snippets only

The upvoted answer did not work for me, here is slightly modified version of this answer that works for me

if ("ga" in window) {
    tracker = ga.getAll()[0];
    if (tracker) {
        tracker.set("page", '/some-page');
        tracker.send("pageview");
    }
}
dav
  • 8,931
  • 15
  • 76
  • 140
2

just do it at the end of your AJAX request:

gtag('config', 'GA_MEASUREMENT_ID', {'page_path': '/new-page.html'});

source: https://developers.google.com/analytics/devguides/collection/gtagjs/single-page-applications

1

You may have problems because those receiving Ajax are not expecting or processing Javascript.

Google has this protocol as a solution:

POST /collect HTTP/1.1 Host: www.google-analytics.com

payload_data

details are here:

https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide#proxy-server-tracking

You will need to use a POST or GET method using your scripting language. If you come up with an answer and working solution, please let me know! I'm doing all I can to get this to work.

  • Thanks for this but the solution has moved on and I am no longer using AJAX. The issue now is that I cannot seem to send multiple track events to analytics. – user2599927 Jun 14 '14 at 09:48
1

Html

<a class="ajax-load" href="home.html" >Home</a>

Javascript

jQuery(document).ready(function($) {
    $(".ajax-load").click(function(event) {
        event.preventDefault();
        var href = $(this).attr("href");
        $.ajax({
            url: href,
            type: 'post',
            dataType: 'html',

        })
        .done(function(response) {
            $(".somediv").html(response);
            // now send page view
            ga('send','pageview','/virtual/....');
        })
        .fail(function() {
            // show error dialog
        })
    });
});
David Newcomb
  • 10,639
  • 3
  • 49
  • 62
Ilyas karim
  • 4,592
  • 4
  • 33
  • 47