I'm making a simple script to save some data on when a user access a page and leaves a page, along with some other page details. The script "works", but it doesn't work all the time. It seems to be working sporadically. I'm not getting console errors on the time it doesn't. The server side works fine.
window.onload = function() {
var timeStarted, i, c, l, timeLeft, pageData;
timeStarted = new Date().getTime();
i = <?php echo $model->id; ?>;
c = <?php echo $model->cat; ?>;
l= <?php echo $model->loc; ?>;
window.onbeforeunload = function(){
timeLeft = new Date().getTime();
pageData = [{name: 'timeStarted', value: timeStarted},
{name: 'i', value: job},
{name: 'c', value: cat},
{name: 'l', value: loc},
{name: 'timeLeft', value: timeLeft}];
// Set url for JavaSCript
var url = '<?php echo Yii::app()->createUrl("item/viewedItemInformation"); ?>';
<?php echo CHtml::ajax(array(
'url'=>'js:url',
'data'=> "js: pageData",
'type'=>'post',
'dataType'=>'json',
)); ?>;
}
}
Note
I've just read this post window.onbeforeunload not working in chrome and I am using chrome. However I seem to get the same results in FF too.
What is the correct away about solving this?
Update I literally couldn't tell you what the situations it does and doesn't work. I am only using this function on item pages. Sometimes when i click on an item page and leave to visit another item it works other times it doesn't it really is that sporadic. What I can say is if I leave the item page for a non item page like the home page, no records are ever recorded.