I want to count how much time visitors spend on a certain page and store it in my MySQL DB.
I thought of just starting a timer on window.onload like this:
window.onload= startCount;
window.onunload= sendCount;
var b=0;
var y;
function startCount() {
document.getElementById('livecount').innerHTML=b;
b=b+1;
y=setTimeout("startCount()",1000);
}
and after the visitor leaves the page (window.onunload), I'm sending the time through an XMLHttpRequest to a PHP file, which will store it in my DB:
function sendCount() {
clearTimeout(y);
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","count.php?q="+b,true);
xmlhttp.send();
}
The problem is it doesn't always work. I would say it works like 3 out of 10 times I try it. Could it be that there is not enough time left for the PHP and SQL to be completely executed?