Track Event in Google Analytics Upon Clicking Form Submit

Track event in google analytics upon clicking form submit

There are only 2 ways to ensure, 100%, that all form submissions (amongst users who have JS enabled and who don't block GA) is as follows:

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

The reason for this is that Google Analytics does not have a callback function, so you can't ever be certain you're capturing all of the submits, even if you put a 10 second lag.

Alternately, you can just pass a GET value to the submitted page and setup a check on that page for the value. If its set, you can send a trackEvent call.

Google Analytics event tracking -Contact Form Submit

The most likely problem here is that your page is being unloaded before the event hit has time to send. When you submit a form on a web page, most browsers will stop executing JavaScript and start loading whatever new page the form's action attribute is pointing to.

The general workaround for this is to call preventDefault on the form's submit event, wait for the hit to successfully send to Google Analytics, and then manually re-trigger the form submit.

Here's how that might look (note: I'm using jQuery for simplicity):

$('#my-form').on('submit', function(event) {
// Prevent the browser's default form submission action.
event.preventDefault();

ga('send', 'event', {
eventCategory: 'Contact',
eventAction: 'Information Request',
eventLabel: 'Contact Form',
hitCallback: function() {
$('my-form').trigger('submit');
}
});
});

The key part in the above code is the hitCallback function, which gets invoked when GA returns success from the event hit beacon.

How to setup event tracking on Google Analytics on form submission?

I can't track a differnt URL after submission, the only option would be to track when a user hits the submit button.

That is a bit of a non sequitur. Even when the Url does not change there is probably some stuff happening - before you send it there is probably some form validation, and there is some action behind the scene to send there form, like e.g an ajax call.

You could attach event tracking to a submit handler:

<form onSubmit="ga('send','event','category','action','label')">
<input type="text" id="text" name="text">
<input type="submit">
</form>

However this would just tell you that somebody hit the submit button, not if they filled in the form correctly or if the form actually has been sent.

Now I enter speculation land, because I do not know how your form actually works - maybe you can show us an url or give more information.

But maybe you have a validation function that is called on the submit action of the form to see if the form is filled in correctly. In that case it would be advisable to do the tracking in the validation function (horribly simplified example, not production code):

<form onSubmit="validate()"><input type="text" id="text" name="text"><input type="submit"></form>

<script>
function validate() {
var test = document.querySelector('#text').value
if(test = "") {
ga('send','event','Form','Submit','Submitted, but not filled in');
return false;
}
ga('send','event','Form','Submit','Submitted with correct values');
return true;
}
</script>

That's a tad better, at least it tracks the difference between correct submissions and invalid submissions.

Even more speculation: If your form is sent without page reloads it uses probably an ajax call, and there is a huge probability that is uses jQuery (I say that because a) it really is probable and b) it's easier to construct an example in jQuery. The same can be achivied with other libraries or in native JS, but the example will produce an error if you do not use jQuery).

jQuery has a thing called "global ajax handlers". "Global" means they are not callbacks for a specific action, they hook into jQuerys ajax "mechanism" whenever a call to an ajax function is made. The following might work if you have only one aja event per page (else you need logic to distinguish the different ajax event e.g, by checking the url they are being send to), and allows you to track if the ajax call has returned successfully, like when your form data has been send to the server and the request return a 2xx status code:

$(document).ajaxSuccess(function() {
ga('send','event','Form','Submit','Yeah, form data sent to the server');
});

However this does not tell you if the data has been processed correctly. For that you need to make the server emit a success message and check the response:

$( document ).ajaxSuccess(function( event, xhr, settings ) {
if ( settings.url == "formprocessor.php" ) {

if(xhr.responseText.indexOf("success") > -1) {
ga('send','event','Form','Response Received','Form data processed ');
} else {
ga('send','event','Form','Response Received','Form data NOT processed ');
}
}
});

The global ajax event handler is attached to the document - you can put that anywhere on your page, it will do nothing unless an ajax event was called.

Again, this is not production code. Do not try to copy and paste.

This was certainly a bit much if you are new to this, but it should at least help you to improve the question and to see what kind of things are possible. If you can share an Url to your form I can possibly improve the answer.

Google Analytics Event tracking with _trackEvent when a form is submitted

Ok looks like its time to answer my own question for the benefit of others:

I did some digging and it was being caused by the page changing location before the event was tracked properly. Thanks to a post by Joel Peterson I came up with this piece of code:

jQuery(document).ready(function($){
$('form').submit(function(event){
//if analytics object exists
if(window._gat){
event.preventDefault();
optinForm = this;
_gaq.push(['_set','hitCallback', function(){
optinForm.submit();
}]);
_gaq.push(['_trackEvent', 'Forms', 'Submit', 'hbsanewtraffic']);
}
//if no analytics object, service as normal
});
});

It uses a callback function to ensure that the event is sent first, and then submits my form.



Related Topics



Leave a reply



Submit