Tuesday, May 14, 2024
 Popular · Latest · Hot · Upcoming
1
rated 0 times [  3] [ 2]  / answers: 1 / hits: 29665  / 10 Years ago, tue, may 20, 2014, 12:00:00

I'm trying to send an event to Google Analytics after a user is registered and before he's redirected.
I'm using Google Tag Manager and universal js.


First, I was trying to use the dataLayer object, as described here: developers.google


Here's what my function looked like:


//Registering new user via ajax
$.ajax('/register/', {
success: function() {

//Pushing event to dataLayer
dataLayer.push({
'Category': 'Registration Process',
'event': 'Registration Submit Btn'
});

//Logging in new user and redirecting the page with a timeout
setTimeout(function(){
loginAction();
}, 500)
}
})

The trouble is that I was receiving just about 25% of all events, all others are lost. I don't know if and when events are actually sent to Google after adding objects to the dataLayer, and I think 75% of events were not send at all.


Now I'm trying to implement another approach:


//Registering new user via ajax
$.ajax('/register/', {
success: function() {

//Sending event through ga('send')
parent.ga('send', 'event', 'Registration Process', 'Registration Submit Btn');

//Logging in new user and redirecting the page with a timeout
setTimeout(function(){
loginAction();
}, 500)
}
})

But ga('send') does not have any callback function again!


How do I make sure that an event was actually sent to Google, using the dataLayer or ga('send')?


More From » jquery

 Answers
23

Finally got it. It's pretty complicated and not described in docs.
In my case I use Google Tag Manager, so there some workarounds I had to make to get successfully fire an event and get callback.



First, we have to get ClientId, which is required with any event sent to Google servers. Actually it's kept in cookies, but Google does not recommend to take it directly from there.



Here is how Google recommends to get it, but this will not work if you are using Google Tag Manager.



 ga(function(tracker) {
var clientId = tracker.get('clientId');
});


Instead, you have to get ClientId from getAll method.



 var clientId = ga.getAll()[0].get('clientId');


After, you have to create new tracker



    ga('create', 'UA-XXX-YYY', {
'clientId': clientId
});


And after that we can send an event:



 ga('send', 'event', {
'eventCategory': 'YOUR Category Name', //required
'eventAction': 'YOUR Action name', //required
'eventLabel': 'YOUR Label',
'eventValue': 1,
'hitCallback': function() {
console.log('Sent!!');
//callback function
},
'hitCallbackFail' : function () {
console.log(Unable to send Google Analytics data);
//callback function
}
});

[#70935] Saturday, May 17, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
hugo

Total Points: 21
Total Questions: 120
Total Answers: 107

Location: Belarus
Member since Tue, Jul 20, 2021
3 Years ago
;