Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught ReferenceError: ga is not defined

I want know how many times people clicked on a particular button (should be very simple with Google analytics). However, I had an "Uncaught ReferenceError: ga is not defined" error from google console and can't find how to fix it.

I added this in the head:

     <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-X', 'auto') ; 

      ga('send', 'pageview');

    </script>

And add an onclick event on the button by generating the code with this tool http://gaconfig.com/google-analytics-event-tracking/contact-form/ :

onclick="ga('send', 'event', { eventCategory: 'Book button', eventAction: 'Click', eventLabel: 'enquiry home page'});"

Then I set up the goals in google analytics, but still have this error in the console.

So I tried to add:

var gaq = gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXXXX-X']);
_gaq.push(['_trackPageview']);

Before declaring the google analytics function, but it generates a second error so I just dropped it.

Does anyone know if the problem comes from the script I'm using? Or if it is from the onclick event code?

like image 829
meij57 Avatar asked Jul 07 '15 16:07

meij57


2 Answers

I created a simple HTML with the same JS and click handler and ran it in my local apache server, it just works fine. Don't see any reference errors.

Make sure you don't have AdBlocker or other software preventing tracking which might be blocking the GoogleAnalytics `

 <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-X', 'auto') ; 

    ga('send', 'pageview');

  </script>

<input type= "button" value ="Click Me" onclick="ga('send', 'event', { eventCategory: 'Book button', eventAction: 'Click', eventLabel: 'enquiry home page'});"/>
like image 179
kiran Avatar answered Nov 14 '22 01:11

kiran


The same problem occured in my Wordpress website. I had event tracking code in my contact form 7 additional field, but after I installed the plugin Monster Insights I had to delete the code in the Theme Options. Forgetting the code in my contact forms, I got this message too.

So delete all tracking code if you start using this plugin. Hope someone finds this information usefull..

like image 4
user7305940 Avatar answered Nov 14 '22 01:11

user7305940