Using Google Analytics on AJAX Requests

There is a mobile optimized version of this page, view AMP Version.

Google Analytics is a great way to track the visitors on your websites, however what if you are using AJAX for website navigation? Fortunately Google have everything under control, you can easily tell Analytics that the user is loading another page by using _trackPageView.

You should already have the latest Google Analytics tracking code called in the head/body of your website:

<script type="text/javascript">
	var _gaq = _gaq || [];
	_gaq.push(['_setAccount', 'UA-xxxxxxxx-x']);
	_gaq.push(['_setDomainName', 'xxxxxxxx.xxx']);
	_gaq.push(['_trackPageview']);

	(function() {
		var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
		ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
		var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
	})();
</script>

So lets say you have the following code to identify URL clicks and use AJAX to load the page content:

$("a").on("click", function(event) {
	$.ajax({
		type: "GET",
		url: url,
		dataType: "html",
		success: function(data) {
			$("#content").html(data);
		}
});

It is really simple to now add the Google Analytics code into your AJAX request:

$("a").on("click", function(event) {
	$.ajax({
		type: "GET",
		url: url,
		dataType: "html",
		success: function(data) {
			$("#content").html(data);
			_gaq.push(['_trackPageview', url]);
		}
});

You should try and get URL so that it is a relative link from the root of your website, for instance /homepage/ for http://mysite.com/homepage/.

If you are sending a full url to your AJAX request, you could perhaps use this solution to get a relative URL:

$("a").on("click", function(event) {
	$.ajax({
		type: "GET",
		url: url,
		dataType: "html",
		success: function(data) {
			$("#content").html(data);
			
			//get relative path
			nohttp = url.replace("http://","").replace("https://","");
			firstsla = nohttp.indexOf("/");
			pathpos = url.indexOf(nohttp);
			path = url.substring(pathpos + firstsla);
			_gaq.push(['_trackPageview', path]);
		}
});

Tip: Put in plenty of alert() debug into the code to make sure you are reporting links / paths correctly to Google Analytics.

Author: Dean Williams

I'm a Web Developer, Graphics Designer and Gamer, this is my personal site which provides PHP programming advice, hints and tips