Reputation: 63619
I have a website page where most of the visitor will spend their time on. The site uses PHP with Codeigniter and jQuery.
Problem: However, I believe tracking systems like Piwik calculate the time spent on a page by subtracting the time the visitor leaves that page to a new page from the time he loads the page.
Is there a way around this? Maybe use javascript to trigger the tracking system so it knows that the visitor is leaving the page?
Upvotes: 1
Views: 5375
Reputation: 5169
Edit: I added some "salting" to the $id, I don't know.. I get the feeling that it's even more unique, even though I think it's a bit unlikely that there will be similar IDs due to the use of micro seconds but just to be extra sure
Something like this
JQuery:
Ajax request to StayAlive.php every 10 seconds
function pingPing(){
$.ajax(
{
type:'GET',
url:'StayAlive.php',
success: function()
{
setTimeout(pingPing, 10000);
}
}
}
PHP: StayAlive.php
<?php
function newUser(){
$id=sha1($_SERVER['HTTP_USER_AGENT'].microtime().$_SERVER['REMOTE_ADDR']);
setcookie("id", $id, time()+3600*24*365);
//create new row in the database for that $id
}
if (isset($_COOKIE["id"])){
//check if the id is in the database
//if yes => time_spent+=10
//if no => newUser();
}
else
newUser();
?>
Upvotes: 2
Reputation: 271
You can use the following to send an Ajax request to a page when the user leaves the page (they don't necessarily have to load a new one).
$(window).unload( function () {
$.ajax({
type: "POST",
url: "yourpage.php",
data: {
command: "disconnect"
},
dataType: "json",
async: false,
success: function(data) {}
});
});
You can create a javascript which generates a timestamp of the user when they load the page, and pass it to a .php page when they leave. Calculate the difference in the timestamps to work out how long they spent on the page.
Upvotes: 2