I'm working on a tracking script for a fairly sophisticated CRM for tracking form actions in Google Analytics. I'm trying to balance the desire to track form actions accurately with the need to never prevent a form from not working.
Now, I know that doing something like this doesn't work.
$('form').submit(function(){
_gaq.push(['_trackEvent', 'Form', 'Submit', $(this).attr('action')]);
});
The DOM unloads before this has a chance to process.
So, a lot of sample code recommends something like this:
$('form').submit(function(e){
e.preventDefault();
var form = this;
_gaq.push(['_trackEvent', 'Form', 'Submit', $(this).attr('action')]);
//...do some other tracking stuff...
setTimeout(function(){
form.submit();
}, 400);
});
This is reliable in most cases, but it makes me nervous. What if something happens between e.preventDefault();
and when I get around to triggering the DOM based submit? I've totally broken the form.
I've been poking around some other analytics implementations, and I've noticed something like this:
$('form').mousedown(function(){
_gaq.push(['_trackEvent', 'Form', 'Submit', $(this).attr('action')]);
});
$('form').keydown(function(e){
if(e.which===13) //if the keydown is the enter key
_gaq.push(['_trackEvent', 'Form', 'Submit', $(this).attr('action')]);
});
Basically, instead of interrupting the form submit, preempting it by assuming that if someone is mousing down or keying down on Enter, than that form is submitted. Obviously, this will result in a certain amount of false positives, but it completely eliminates use of e.preventDefault();
, which in my mind eliminates the risk that I might ever prevent a form from successfully submitting.
So, my question:
Them fellers over at that there Googleplex are awful bright and they figgered some day somethin' like this was bound to happen and now, sure enough, it has. Why don't you give this a good try:
$('form').submit(function(e){
e.preventDefault();
var form = this;
_gaq.push(['_trackEvent', 'Form', 'Submit', $(this).attr('action')]);
//...do some other tracking stuff...
_gaq.push(function(){
form.submit();
});
});
That _gaq.push
thigamajigger executes its elements sequentially, so you should be jest fine.
And no, I don't know why I suddenly started talking like this.
I use a different approach, and generate the event tracking script in the page resulting from the submit. You could call it deferred event tracking.
I wrote a blog post with all details about my approach to event tracking in backend actions. It is biased towards Java-Struts, but you can get the general idea.
The rationale is that I want to track some things after they happened at the server side. In this kind of case, after the form was submitted and processed by the server.
What I do (very summarized):
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With