I have an input button which has google analytics code (click detection) :
<input type="button" onclick="ga('send',...);"/>
This button is not submitting , and I do see the request to google's servers in the network panel.
The problem is when the button is a submit button :
<input type="submit" onclick="ga('send',...);"/>
It doesn't work , I know.
I could solve it via : jQ solution : ( for example)
e.preventDefault();
ga('send',...);
$(this).click();
But I'm not after the solutions. I'm after the reason why it's happening.
The obvious reason is that because the page redirects/posted.
But in the same breath I could do :
<input type="submit" onclick="for (var i=0;i<5;i++) console.log(i);"/>
The code works : ( just like I could write return false
)
It displays the numbers and submit
I know that ajax is an async operation(should be) , but what happens internally that prevent the request from executing ? (as opposed to other js code)
notice : I don't care about the response. The request has a query string with data. google servers waits for this request with query string. ( google dashboard doesn't show any clicks being received)
(this question has come up after I was required to put click detection on certain buttons ( which some do submit) , and after checking , google doesn't say anything about those kind of buttons )
Not an Explanation( as I wanted) but a solution to the google analytic problem when submitting /redirecting :
Include this code at the bottom :
$("body").on('click', '[data-ga]', function (e)
{
var _ = $(this);
if (_.data('prevented') == 1)
{
_.removeData("prevented");
return true;
}
e.preventDefault();
_.data('prevented', 1);
window.__gacb = function () { _[0].click(); };
new Function(_.data('ga'))();
return false;
});
And for any element which submits/redirects :
<input type='submit' data-ga="ga('send', 'Forms', { 'hitCallback':function (){window.__gacb()}});" />
google has this property hitCallback
which is a callback , so I can trigger the click myself after recognizing it was prevented by me at the first time.