Steps for implementing AJAX call tracking with Google Analytics

After setting up my Google Analytics account and adding the provided code to my index.php file, I noticed calls to www.google-analytics.com in Firebug. It seems like everything is working correctly.

Now, I want to track how many times the 'functions.php' file is called through AJAX from the index file.

I attempted to use

_gaq.push(['_trackPageview', 'functions.php']);
but encountered an error stating
Uncaught ReferenceError: _gaq is not defined
. To address this, I included var _gaq = _gaq || []; in my code, which resolved the error. However, I am now unable to see any requests to www.google-analytics.com after the AJAX request completes.

If anyone could assist me in configuring analytics to track AJAX calls, I would greatly appreciate it.

This is how my code appears:

<script type='text/javascript'>
  (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-1234556-1', 'domain.com');
            ga('send', 'pageview');

         var _gaq = _gaq || [];

        function submit_data(){

                var text_area=$('#textarea').val();
                var url ="functions.php";
                jQuery.ajax({
                    type: "get",
                    dataType: "text",
                    url: url,
                    data: {
                        what : "generate",
                        text_area: text_area,
                        t: Math.random()
                    },
                        success: function(data, textStatus){
                        $('#textarea').val(data);
//                      _gaq.push(['_setAccount', 'UA-12345-1']);
                        _gaq.push(['_trackPageview', 'functions.php']);
                        }
                });
        }

        </script>

Answer №1

In Google Analytics, make sure to select "Universal Analytics" during check-in as it utilizes a new code counter. Check the browser DOM for the absence of the "_gaq" object, as this indicates an error. Attempting to resolve this by creating an empty array (_gaq) will not work.
Here is the old code:

var _gaq = _gaq | | [];
_gaq.push (['_setAccount', 'UA-XXXXXX-1']);

Avoid using the old code! Also, do not use multiple code counters like 'UA-XXXXXX-1' - that's a mistake)
Here is the updated code:

ga ('create', 'UA-XXXXXXX-1', 'mysite.com');
ga ('send', 'pageview');

The new Google Analytics counter comes with a new syntax.
Refer to the documentation for event usage: https://developers.google.com/analytics/devguides/collection/analyticsjs/events
Example of implementation:
Imagine having a calculator on your page and wanting to track events triggered by button clicks on it.
Category - "Using the Calculator";
Event - "Calculating the cost".
Old code:

_gaq.push(['_trackEvent', 'Using the Calculator', 'Calculating the cost');

New code:

ga('send', 'event', 'Using the Calculator', 'Calculating the cost');

Ensure Category and Event are specified!
P.S.: Apologies for any language barriers; I relied on Google Translate for assistance :)

Update:

<script type='text/javascript'>

  (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');
//Include once per page
        ga('create', 'UA-1234556-1', 'domain.com');
        ga('send', 'pageview');
        //
        function submit_data(){

                var text_area=$('#textarea').val();
                var url ="functions.php";
                jQuery.ajax({
                    type: "get",
                    dataType: "text",
                    url: url,
                    data: {
                        what : "generate",
                        text_area: text_area,
                        t: Math.random()
                    },
                        success: function(data, textStatus){
                        $('#textarea').val(data);
                        ga('send', 'event', 'MyCategory', 'functions.php');
                        }
                });
        }

</script>

Answer №2

When working with Universal Analytics (analytics.js), make sure to replace the following:

_gaq.push(['_trackPageview', 'functions.php']);

with this:

ga('send', 'pageview', 'functions.php');

Answer №3

It appears that there is a mix of Universal Analytics (analytics.js and ga() calls) with Async Analytics (ga.js and _gaq.push()), however, the code to initialize ga.js is missing.

To correct this, update the code as follows

var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-12345-1']);
_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);
})();

Answer №4

A simple solution is to include the following code snippet right after your Google Analytics script in order to establish the _gaq array:

var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-98765-4']);
_gaq.push(['_trackPageview']);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering an error with requireJS: "Unknown provider $routeProvider with AngularJS 1.2.9 ngRoute"

Currently, I am utilizing angularJS-1.2.9 and angular-route-1.2.9 to configure routes for my application. Additionally, I have integrated requireJS as the dependency loader to modularize the code. Despite adding the ngRoute dependency into the AngularJS co ...

Installing different versions of a package in npm can be done by loading multiple versions

I am in the process of setting up a web API and I want to provide support for various versions of the underlying library. In essence, I would like to access it through: where x.y.z represents the version of the library I am utilizing. Using npm for mana ...

incorrect path in post request

I encounter a dilemma when using a form to edit and update data via ajax in my application. The form can be used for both creating and updating records, which is determined by a ViewBag variable in the view like so: <form asp-action=@(ViewBag.Mode == " ...

While looping through a JSON object and converting it to a string, the script is causing

I'm facing an issue with my webpage where I retrieve a JSON object from a URL and convert it into a string. Depending on whether the string is true or false, I want the div to either fade or remain unchanged. The JSON object obtained from the URL loo ...

Removing the root component in ReactJS can be done on specific pages by implementing

Is there a way to remove the <header/> and <footer/> components from my signup.js and signin.js pages without altering the root index.js file? Presently, the root index.js file looks like this: class Template extends React.Component { render( ...

Issue arising from the lack of direct communication between parent and child elements

I am facing an issue with indirect communication in a react native application. The situation involves a parent component, implemented as a class component, and a child component, which is a functional component. Here is the Parent component: constructor ...

The art of building websites and applications for the

Greetings to everyone! I am a beginner in the field of web development and I find myself facing some uncertainties. A few weeks ago, I embarked on creating a website using HTML, CSS, and JS but now I'm at a loss for how to proceed. What should be my n ...

How to make a div slide up using jQuery without obstructing text

A scenario is presented where HTML contains two div elements, one with text and the other hidden initially. The goal is to make the second div slide up from below the first div to create a new background color effect. While sliding up works successfully, ...

Issue with jQuery, Ajax, and Haml as js.erb files are not triggering

After researching various sources, it seems like this issue needs to be addressed once more. When coding in Rails3, I am attempting to incorporate smooth Ajax effects when a user attempts to create a post on a different element of my application. Here&apos ...

Updating DOM element value from controller in AngularJs following an AJAX request

Currently, I am facing an issue in my code where I want to display a progress bar and hide it until isLoaded becomes true. <uib-progressbar class="progress-striped active" value="100" type="warning" ng-hide="{{isLoaded}}"></uib-progressbar> I ...

Angular 2 Element Selection: Dealing with Unrendered Elements

This form consists of three input fields: <div> <input *ngIf = "showInputs" #input1 (change)="onTfChnage(input2)" type="text"/> <input *ngIf = "showInputs" #input2 (change)="onTfChnage(input3)" type="text"/> <input *ngIf = "showInp ...

What is the best method for updating a PHP variable in a SQL query?

I am working on a project that involves displaying reporting data from an SQL table in an HTML table. Currently, the query is set to display data for the current date. However, I am exploring efficient ways to update the start and end date variables as wel ...

Tips for displaying a category name only once if it has already been rendered in a map function

My scenario involves a variety of categories in which pharmaceutical drugs are classified. Each individual drug belongs to a specific class. Currently, my code iterates through all the categories from the category array and places drugs underneath them if ...

The ValidationMessageFor() in MVC 3 is not showing up as expected

I need to ensure that dates are entered in the format dd-mmm-yyyy. I found a helpful post that serves as a guide: Issue: The ValidationMessageFor text is not showing up (on both postback and client side). Any suggestions? Update: By incorporating @Darin ...

Simultaneously opening the second submenu and closing the previous submenu with a height transition results in the second submenu being positioned off-screen

Sample: https://codesandbox.io/p/sandbox/navbar-k2szsq (or refer to the code snippet below) In my navbar, I have implemented multiple submenus with a height transition when the user opens or closes a submenu. However, only one submenu can be open at a tim ...

What is the best way to retrieve an object from the state in my React application?

I have been struggling to locate an item from a collection so that I can update my react component. Despite the fact that the propertyState object is not empty and contains a list that I have successfully console logged, I keep receiving an undefined obj ...

Ways to customize the design of a bootstrap button using jQuery

<a class="btn btn-small btn-block btn-warning" type="button" id="999">&nbsp;</a> Looking to customize the button style? Check out http://getbootstrap.com/2.3.2/base-css.html#buttons I'm interested in changing the button's style ...

Tips for transferring an id from an HTML form to Node.js and MySQL

Below is the HTML form that allows input of a client ID via a dropdown menu. The selected client ID from the dropdown will be passed through the form: <form action="/query" method="get"> <select name="client_id" required=""> ...

Tips on how to hold off the display of webpage content until all elements, including scripts and styles, have fully loaded

I have a variety of div elements set up like this - <div id='1' class='divs_nav'>My Dynamic Content</div> <div id='2' class='divs_nav'>My Dynamic Content</div> ... <div id='149' c ...

Switch up the current Slick Carousel display by utilizing a div element

We have implemented the slick carousel to show only one slide at a time within the <div class='item__wrapper'>. Beneath this are three items, and we want the slick carousel to update when any of these items are clicked. Issues Using item ...