Track an event in Google Analytics when you click submit

I need to track an event in Google analytics when someone fills out a form and clicks submit. The resulting page that appears is a standard page such as a toolbar, so in order to track the event on this page, I will need to pass the event to the URL and then read the URL and output the Google Analytics javascript event tracking code based on it . This is a frequently marked page, although a page that reloads, clicks on it, etc. Therefore, I would prefer not to send tracking events to the URL and not spoil the analytics.

Instead, I would rather do something like the following jQuery code on a page with a form:

$('#form_id').submit(function() { _gaq.push('_trackEvent', 'my category', 'my action'); }); 

The problem I'm afraid of is that I will miss some tracked events because right after calling this javascript the browser will submit the form and go to another web page. If the utm.gif tracking image is not loaded on time, I will skip the event: (.

Is my fear justified? How can I not skip tracking events?

+61
javascript jquery analytics google-analytics
Nov 03 '10 at 11:30
source share
9 answers

There are only 2 ways to ensure that 100%, that all forms of submission (among users who have JS enabled and who do not block GA), are as follows:

  • You can do an AJAX submit, and then not worry about changing the page and thus have all the time in the world for GA to process AND your new page is loading instead of the old.
  • You can force the form to open its action in a new window, leaving all background processes on the main page and preventing the race condition that you are worried about.

The reason for this is that Google Analytics does not have a callback function, so you can never be sure that you capture all shipments, even if you set a 10-second lag.

Alternatively, you can simply pass the GET value to the presented page and configure the verification of this page for the value. If it is set, you can send a call to trackEvent.

+17
Nov 13 2018-10-11
source share

Use Google Analytics hitCallback

You can specify a custom callback function in the tracker object.

 _gaq.push(['_set', 'hitCallback', function(){}]); 

The callback is called after "luck sent successfully."

If you want to track the click on the submit button and submit the form after that, you can use the following code (uses jQuery) for your event:

 var _this = this; // The form input element that was just clicked _gaq.push(['_set','hitCallback',function() { $(_this).parents('form').first().submit(); // Submit underlying form }]); _gaq.push(['_trackEvent', 'My category', 'My action']); return !window._gat; // Ensure that the event is bubbled if GA is not loaded 

Or like onclick one insert for your <input type="submit"> element:

 onclick="var _this=this;_gaq.push(['_set','hitCallback',function(){$(_this).parents('form').first().submit();}]);_gaq.push(['_trackEvent','My category','My action']);return !window._gat;" 

What he does to track the My category/My action event, uses jQuery to find the submit button's main form element, just clicked, and then submit the entire form.

See: Google Analytics - Submitting data to Google Analytics - Hit callback (thanks to superacuo)

UPDATE If you use modern analytics.js code with a specific ga () function, you can write the following:

 var _this = this; ga('send', 'event', 'My category', 'My action', { 'hitCallback': function() { $(_this).parents('form').first().submit(); } }); return !window.ga; 
+143
Sep 17 '12 at 14:34
source share

For those who deal with universal google analytics and do some trick with hitCallback (fx track event after validation, but before submitting the form), keep in mind that google-analytics.js could potentially be blocked, however the ga function will is still defined, so submit will not.

 ga('send', 'pageview', event, { 'hitCallback': function() { _this.submit(); } }) return !window.ga; 

Can be fixed with a check that checks if ga is loaded

 ga('send', 'pageview', event, { 'hitCallback': function() { _this.submit(); } }) return !(ga.hasOwnProperty('loaded') && ga.loaded === true) 
+12
Jul 07 '14 at 14:30
source share

This question has been around for several years now, and it seems that Google Analytics has provided the opportunity to do this without the hackers mentioned above.

From Google Analytics docs :

In addition to arrays of commands, you can also push function objects into the _gaq queue. Functions can contain any arbitrary JavaScript and similar arrays of commands, they are executed in the order in which they are placed on _gaq.

You can combine this with pressing a few commands to make aboslute sure that they are added in order (and save the call).

 $('input[type="submit"]').click(function(e) { // Prevent the form being submitted just yet e.preventDefault(); // Keep a reference to this dom element for the callback var _this = this; _gaq.push( // Queue the tracking event ['_trackEvent', 'Your event', 'Your action'], // Queue the callback function immediately after. // This will execute in order. function() { // Submit the parent form $(_this).parents('form').submit(); } ); }); 
+7
Nov 01 '12 at 14:40
source share

If you are not too concerned about 100% accuracy, you can simply delay the 1 second delay.

 $('#form_id').submit(function(e) { var form = this; e.preventDefault(); // disable the default submit action _gaq.push('_trackEvent', 'my category', 'my action'); $(':input', this).attr('disabled', true); // disable all elements in the form, to avoid multiple clicks setTimeout(function() { // after 1 second, submit the form form.submit(); }, 1000); }); 
+6
Nov 03 '10 at 11:51 on
source share

If the hitCallback solution is good, I prefer to set a cookie and fire the event from the next page. Thus, a failure in GA will not stop my site:

 // Function to set the event to be tracked: function setDelayedEvent(category, action, label, value) { document.cookie='ev='+escape(category)+'!'+escape(action)+'!'+escape(label)+'!'+value +'; path=/; expires='+new Date(new Date().getTime()+60000).toUTCString(); } // Code run in every page, in case the previous page left an event to be tracked: var formErrorCount= formErrorCount || 0; var ev= document.cookie.match('(?:;\\s*|^)ev=([^!]*)!([^!]*)!([^!]+)!([^!]+)(?:;|\s*$)'); if (ev && ev.length>2) { _gaq.push(['_trackEvent', unescape(ev[1]), unescape(ev[2]), unescape(ev[3]), parseInt(ev[4])]); document.cookie='ev=; path=/; expires='+new Date(new Date().getTime()-1000).toUTCString(); } 
+6
May 16 '13 at 7:02
source share

When it is important to track each submission, I usually set a cookie on the backend with all the necessary data. Then configure the rule in GTM to disable the tag based on the existence of this 1st party cookie. The tag parses the cookie for the required values ​​and does everything that is required of them, and deletes the cookie.

A more sophisticated example is shopping tracking. You want to disable 5 different tags when a user makes a purchase. Race conditions and an immediate redirect to any welcome page make it difficult to use simple onSubmit tracking. Therefore, I set a cookie with all the data associated with the purchase, and on any page that the user finishes on GTM, it recognizes the cookie, the entry point tag will trigger, which will analyze the cookie, click all values ​​on the dataLayer, delete cookies and then the tag itself will push events in the dataLayer, thereby causing 5 tags that require purchase data (which are already in the dataLayer).

0
Nov 27 '14 at 13:25
source share

Well, since we switched to universal analytics, I would like to answer the same as GTM and UA.




GTM :

Tracking an event in Google Analytics when you click submit is pretty simple using GTM.

  • Create a UA tag and set the event type to GTM.
  • Fill in the required action, category and event label
  • Create a trigger of type Form Submission.
  • Place more conditions to target the desired button.

This is the best, optimal and convenient approach for OP.

enter image description here

0
May 23 '17 at 5:13
source share

Here's how you perform event callbacks in gtag.js to ensure that Google Analytics data is sent before changing the page URL:

 gtag('event', 'view_promotion', { myParameter: myValue, event_callback: function () { console.log('Done!'); // Now submit form or change location.href } }); 

Source: https://developers.google.com/analytics/devguides/collection/gtagjs/sending-hits

0
Nov 02 '17 at 9:27
source share



All Articles