1

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 :

  • for a reference http://stackoverflow.com/questions/4667068/how-to-measure-a-time-spent-on-a-page – Dhara Jan 21 '16 at 09:57

1 Answers1

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');
        }
    });
});
  • i Fixed it but still not Working – bilel mkadmi Jan 21 '16 at 10:07
  • Then, my friend, you'll have to be more specific as to what problem you're experiencing as this solution works fine on my end. I should probably 've setup a codepen but seeing what time and effort you put in asking the question I felt I went at length already. – Sietse̩̯ van der Meer Jan 28 '16 at 12:01