bilel mkadmi
bilel mkadmi

Reputation: 11

Count the time spent by visitor on my website using AJAX

Can someone help me with my script Ajax? I want to count the time spent by a visitor on my website and send the variable to a PHP page :

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
var start;

$(document).ready(function() {
start = Date.getTime();

$(window).unload(function() {
  end = Date.getTime();
  $.ajax({
    url: 'timer.php',
    type:'POST',
    async: false,
    data: {
            'timeSpent': end - start,
            x:'hello'
          }
  })
});
}

and in timer.php i put :

Upvotes: 1

Views: 607

Answers (1)

It appears you've mistyped your type attr: type='POST' should be type: 'POST'

EDIT: on closer look (moreover, inspection in the DevTool of your choice), more appears..

1) start = Date.getTime(); is not going to work for you. Start with assigning a new Date() object to a startDate variable, then assign its getTime() return to your variable start You should do the same for your end variable value, which by the way you'd preferably define by calling var end, just like you did with start. Not all browsers are strict in respect to this, but it will do wonders for your code/coding consistency.

2) The window unload event listener chunk does not have to be within the document ready listener, which also it seems you overlooked to properly close..

So try this:

var start, end, timeSpent;

$(document).ready( function() {
    var dStart = new Date();
    start = dStart.getTime();
});

$(window).unload(function() {
    var dEnd = new Date();
    end = dEnd.getTime();
    timeSpent = end - start;
    $.ajax({
        url: 'timer.php',
        type: 'POST',
        async: false,
        data: {
            timeSpent:  timeSpent,
            x:          'hello'
        },
        success: function(){
            console.log('yay');
        }
    });
});

Upvotes: 1

Related Questions