Jack7890
Jack7890

Reputation: 1371

Google Analytics pageTracker function doesn't work when loaded via AJAX

I posted on this a while ago, and have since done more research and advanced the problem, but I still don't have a solution...

I have a site (www.seatgeek.com) where a lot of links are loaded via AJAX. When a user clicks on one of these links I want to count it as a goal, so I've tried attaching pageTracker._trackPageview() to the links' onClick attribute. But GA isn't recording these clicks, and I have no idea why. Here's the code for one of these links:

<a href="<?php echo $tickets[$x][3] ?>" target = "_blank" class="buyTicketsLink" onClick="pageTracker._trackPageview('/outgoing/event4.php');">BUY TICKETS</a>

I've tried the above code in situations where the link is not loaded via AJAX and it works fine, so it's definitely a problem specific to AJAX. Also, in my attempts to solve this problem I've also tried adding the onclick events programmatically, e.g.:

<script>
function attach_goal_tracking() {
var links = document.getElementsByClassName("buyTicketsLink");
for(var i=0; i<links.length; i++) {
links[i].onclick = record_goal;
}
}

function record_goal() {
pageTracker._trackPageview('/event/outgoing');
}
</script>

This doesn't work either. But when I add a test alert box to the record_goal() function, it's clear that the function is getting run. For example, if I change the function to this:

function record_goal() {
alert('Hello');
pageTracker._trackPageview('/event/outgoing');
}

Then the 'Hello' alert box displays when a link is clicked. But the pageview to '/event/outgoing' still is not recorded.

I'm completely baffled by what might be causing this. Any advice would be greatly appreciated.

Upvotes: 2

Views: 4416

Answers (3)

Dzion
Dzion

Reputation: 1080

If you're still using the asynchronous method of loading Google Analytics, the following snippet will accomplish the same task:

_gaq.push(['_trackPageview', '/anything']);

or (@Lauren code)

onClick="_gaq.push(['_trackPageview', '/outgoing/event4.php']); return false">

Upvotes: 1

Lauren
Lauren

Reputation: 121

Try adding "return false" after your trackPageView() call, so...

onClick="pageTracker._trackPageview('/outgoing/event4.php'); return false">

Our Analytics rep recommended this to me and it worked like a charm. "return false" usually says, "hey don't pay attention to the href" (I thought, anyway), but my implementation is working just fine.

Hope this helps!

Upvotes: 1

Prem
Prem

Reputation: 16239

Are you using a JavaScript library such as Prototype? document.getElementsByClassName is not a standard JavaScript DOM method.

Do you get any JavaScript errors? E.g. open up Firebug or the Firefox Error Console.

In Firebug, if you type pageTracker; in the console, does it tell you that pageTracker is definitely a function and not undefined?

Upvotes: 1

Related Questions