Is there any way to detect when ga send is finished (promise, callback, event, etc.)? - google-analytics

I need to send an event using ga(), then immediately redirect to another page. If the ga() send isn't complete it is cancelled by the redirect. Is there any mechanism (such as a callback) that I can use to detect when the event has been delivered to GA (or errored out)? I am currently just delaying for a small period of time, but that is non deterministic.

There is (and it is even called callback): Hit Callback. Redirecting after the tracking call indeed the major usecase. E.g the documentation from the example deals with intercepting a form submit, and resubmitting after the form has been sent:
// Gets a reference to the form element, assuming
// it contains the id attribute "signup-form".
var form = document.getElementById('signup-form');
// Adds a listener for the "submit" event.
form.addEventListener('submit', function(event) {
// Prevents the browser from submitting the form
// and thus unloading the current page.
event.preventDefault();
// Sends the event to Google Analytics and
// resubmits the form once the hit is done.
ga('send', 'event', 'Signup Form', 'submit', {
hitCallback: function() {
form.submit();
}
});
});

Related

Track GA4 custom event

I am sending a custom event ("ebook") with a parameter ("titolo") to GA4. After that, I have set the parameter as a Custom Dimension in GA UI.
I am sending the event from my website with this code:
function ebooksGA4new(title) {
gtag('event', 'ebooks', {
'titolo': title
});
}
Then I have set an Exploration on the custom dimension, but after 3 days it still reports "not_set. If I fire the event, I can see it in the real-time report.
Here are 2 ways to find out why
Modify the code a bit, make sure it won't trigger the event if it doesn't have title parameter.
But please make sure this is what you want. You need to decide it is ok or not to receive the event without title parameter.
function ebooksGA4new(title) {
if(!title || title=="")
return false;
gtag('event', 'ebooks', {
'titolo': title
});
}
Open the chrome devtool or something similar with it. Here is the screenshot about how to check it. This should appear on your GA4 real time report as well.

Social shares tracking in GA

This is pretty much covered topic for original FB/Twitter buttons. But what if I have my own "share on fb" button? Like this:
<div id="fb_share"><a target="_blank" href="http://www.facebook.com/share.php?u=blah-blah">Share on FB</a></div>
so I've come up with the folloing solution:
var FBbtn = document.getElementById("fb_share");
FBbtn.addEventListener('click', function() {
ga('send', 'social', {
'socialNetwork': 'facebook',
'socialAction': 'share',
'socialTarget': window.location
});
//console.log('tracked');
});
That is placed AFTER the Google Analytics code.
Despite the fact it wont catch FB callback - it is supposed to do the trick but for some reason I still cannot see any results in Analytics so the question is this: will the solution actually work? In fact it could be even like this I believe:
FB
Your 'share on Facebook' links causes the page to navigate (and not open a new window/tab). When this navigation happens, most mainstream browsers cancel all pending HTTP requests for the current page and then navigates to the new page (fb.com)
In this scenario, one of the pending HTTP requests will be the GA event tracking call which will therefore never complete and never be received by the GA servers.
What you need to use is the GA hit callback functionality, this essentially cancels the native navigation (to FB), sends the tracking call and waits enough time for it to complete and then does a JavaScript redirection to the next page.
You should read the google docs here
In your case your event tracking function should be similar to this:
var FBbtn = document.getElementById("fb_share");
FBbtn.addEventListener('click', function() {
ga('send', 'social', {
'socialNetwork': 'facebook',
'socialAction': 'share',
'socialTarget': window.location,
'hitCallback': function(){
window.location = this.href;
}
});
//console.log('tracked');
return false;
});
So I've made the following changes:
Added the hitCallback property to the event tracking call. this is an anonymous function that is called once the GA servers have sent their response to the event tracking.
added a 'return false' statement which cancels the native functionality and then relies on the hitCallback function to do the navigating.

Change action in Contact Form 7

Would modify the action of Contact Form 7 once sent the mail.
I follow this post and woks fine. But my fom is in a Bootstrap Modal, and I wish they would keep open on submit.
My code is.
In function PHP
add_filter('wpcf7_form_action_url', 'wpcf7_custom_form_action_url'); function wpcf7_custom_form_action_url() { return 'http://saviacomunicacion.com.ar/test2014#sala-de-prensa'; }
And in the Aditional Settings field
add_filter('wpcf7_form_action_url', 'wpcf7_custom_form_action_url');
This redirect the URL, but it´s not sending the mail.
I wish i could send the mail and keep the modal open to show the response: Your mail was send correctly.
Thanks
According to the doc there is another way to accomplish the redirect. Just add some piece of code to the plugin dashboard.
Or you can do custom js function
in the plugin options
on_sent_ok: "customFunction();"
and somewhere in the code
<script>
function customFunction() {
// show your modal here
$('#myModal').modal();
}
</script>
I found my solution with this code. When form submit, the Modal closes after 1 second.
Instead of keeping Modal open, i wait 1 second after close, to show the response of the sending.
j(".form-horizontal").live("submit", function(){
j.post(this.action, j(this).serialize(), function(){
//this callback is executed upon success full form submission close modal here
}, "script");
//this is to wait 1 second until close
setTimeout(function() {j('.modal').modal('hide');}, 1000);
return false;
});

Google Analytics event tracking -Contact Form Submit

I am trying to track when a user clicks on the submit form button and they send contact information. I have this code on the contact page:
<input type="submit" value="Send" class="btn big btn_submit_form" onClick="ga('send', 'event', { eventCategory: 'Contact', eventAction: 'Information Request', eventLabel: 'Contact Form'});">
I am using Universal Analytics.
In my Google Analytics account, I have the goal description Name as Contact Form Submit, and the Goal Type is Event. The event conditions are as follows:
Category -Equals to- Contact
Action -Equals to- Information Request
Label -Equals to- Contact Form
with the Value field being left empty.
I have "Use the Event value as the Goal value for the conversion" set to yes.
However, Google Analytics doesn't seem to be tracking the event. Any idea how to fix this?
Thanks.
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.
Maybe try changing the event to the form submit, instead of the button click:
<form onSubmit="ga('send', 'event', { eventCategory: 'Contact', eventAction: 'Information Request', eventLabel: 'Contact Form'});">
The form can be submitted in ways other than the clicking the submit button (for instance pressing enter in an input field)
Also, in my experience, the tracking will post correctly almost every time, even when you do not call preventDefault on the event.

Node.js HTTP: request 'end' event is never called

I have a client that is sending data chunks to my node.js server.
I want to listen on the "end" event and retrieve the accumulated request body.
Here is my code:
app.post('/users', function(req, res){
req.on('end', function() { // WHY IS THIS NEVER FIRED?
console.log(req.body);
res.send({
"status": "ok"
});
});
});
The problem is that the 'end' event is never fired.
Anyone knows why?
Also, if I do in this way, will the req.body be the accumulated body of all the body chunks?
Basically http POST only fires when you POST to the server. I can't be certain, but I'm assuming you are just attempting to visit server:port/users in your web browser and fail to get a response. By default the web browser is GETing the server. To fix this you have two options.
1. If you change app.post to app.get the event will correctly fire when you visit /users
2. Or you can fire the post function using a form. For example the following code will display a form if you visit the page using GET. When you submit the form it will fire POST.
var express = require('express'),
app = express.createServer();
app.listen(1337, "127.0.0.1");
app.get('/users',function(req,res){
res.send('<form method="post" action="/users"><input type="submit" value="Submit" /></form>');
})
app.post('/users', function(req, res){
req.on('end', function() {
console.log('success');
res.send('success!!!');
});
});
I encountered the same problem, and found this discussion helpful:
My http.createserver in node.js doesn't work?
Simply put, by inserting the line:
request.on("data",function() {})
inside the .createServer loop but after the request.on loop made it work.

Resources