21

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.

1
  • 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
    Commented Jun 13, 2014 at 6:34

5 Answers 5

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/

9
  • 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. Commented Jun 13, 2014 at 7: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. Commented Jun 13, 2014 at 7: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? Commented Jun 13, 2014 at 8: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 :) Commented Jun 13, 2014 at 8: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? Commented Jun 13, 2014 at 8:36
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");
    }
}
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.

1
  • 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. Commented Jun 14, 2014 at 9: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
        })
    });
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.