Google Analytics: Error: ‘_gat’ is not defined

June 8th, 2009

I recently tried to set up Google Analytics on our website. I got the normal page tracking set up fine, but I wanted a way to track customer orders.

I found this article on the WHMCS website explaining how to get order tracking set up using the Google Analytics “E-Commerce” feature. Great I thought! However, when I put the code on to our order complete page, the orders weren’t being tracked and I was receiving this error in my browser:

Error: ‘_gat’ isĀ  not defined

My Googling efforts weren’t turning up much – lots of results for the error, but most due to misspellings etc. I eventually found one result which was helpful to me. Apparently using document.write isn’t good and can turn up issues with ga.js being parsed *after* the rest of the Google Analytics code gets run. This is obviously a big problem :)

The solution? Simply use this code instead:

<script type=”text/javascript” src=”https://ssl.google-analytics.com/ga.js”></script>
<script type=”text/javascript”>
var pageTracker = _gat._getTracker(“UA-XXXXX-X”);
pageTracker._trackPageview();
pageTracker._addTrans( “{$orderid}”, “”, “{$amount}”, “0″, “0″, “{$city}”, “{$state}”, “{$country}” );
pageTracker._addItem( “{$orderid}”, “{$packageid}”, “{$name}”, “{$type}”, “{$amount}”,”1″ );
pageTracker._trackTrans();
</script>

If you are wanting to use the non-SSL version of ga.js, then replace the first line above with this:

<script type=”text/javascript” src=”http://www.google-analytics.com/ga.js”></script>

The above code is for WHMCS, but you can adapt it for general use – essentially, just make sure that you remove the document.write lines and replace it with a new script tag containing the URL to the ga.js script as a parameter.

Share and Enjoy:
  • Digg
  • Twitter
  • Facebook
  • del.icio.us
  • Slashdot
  • Reddit
  • Sphinn
  • StumbleUpon
  • Mixx
  • Blogplay
  • Suggest to Techmeme via Twitter
  • Print
  • Google Bookmarks