Reputation: 4648
I have a form that submits to another domain I do not own and need to track the event in Google Analytics. I'd rather do it without jQuery to avoid a dependency but I'm failing to understand why this code doesn't work:
<form action='example.com/search' onsubmit='trackSubmit()' id='frm'>
<button type='submit'>Search</button>
</form>
<script type='text/javascript'>
function trackSubmit(e) {
var bForm = document.getElementById('frm');
bForm.addEventListener('submit', function(e){
e.preventDefault();
_gaq.push('_trackEvent', 'Foobar', 'Foobar Form Submit');
setTimeout(function(){
console.log('tracking foobar');
bForm.submit();
}, 1000);
}, false);
}
</script>
Upvotes: 2
Views: 7637
Reputation: 6749
For the users who have stumbled to this question and are using new version of google universal analytics. This is the code for submit button and link click
<script type='text/javascript'>
function trackSubmit() {
ga('send', 'event', 'button', 'click', 'searchsubmit', 4);
alert('testing send event')
}
function trackClick() {
ga('send', 'event', 'button', 'click', 'This is coool');
}
</script>
<body>
Pushing data.......
<form onsubmit='trackSubmit()' id='frm'>
<button type='submit' id= 'searchsubmit'>Search</button>
</br>
<a href='http://cool.com' onclick="trackClick(); return false;">cool</a>
</form>
</body>
I have put an alert to display that the events are being fired because when the page submits and you will look at console in debugger, your event will not be visible.
Upvotes: 0
Reputation: 21
This will be reusable for multiple submission tracking.
<script type="text/javascript">
function trackSubmissions(form, category, name, value) {
try {
_gaq.push(['_trackEvent', category, name, value]);
} catch(err){}
setTimeout(function() {
form.submit();
}, 100);
}
</script>
<form onsubmit="trackSubmissions(this, 'category', 'name', 'value'); return false;">
</form>
Upvotes: 1
Reputation: 6229
onsubmit='trackSubmit()'
and bForm.addEventListener('submit', function(e){
This seems to be the wrong part. If you call trackSubmit()
on submit
, then adding a listener inside this function is useless, it doesn't even fire. I believe it should be just:
<form action="http://example.com/search" onsubmit="return trackSubmit()" id="frm">
<button type="submit">Search</button>
</form>
<script type="text/javascript">
function trackSubmit() {
var frm = document.getElementById('frm');
_gaq.push('_trackEvent', 'Foobar', 'Foobar Form Submit');
setTimeout(function(){
console.log('tracking foobar');
frm.submit();
}, 1000);
return false;
}
</script>
Upvotes: 4