Problem getting access time

3

I'm trying to catch the time that the surfer remained on the page, however nothing is returned.

Main php file:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Introdução</title>

<!--<script src="https://code.jquery.com/jquery-1.10.2.js"></script>--><scriptsrc="jquery-3.1.1.js"></script>
<link href="style.css" rel="stylesheet" type="text/css">

<script type="text/javascript">
var inicio;
$(document).ready(function(){
    inicio = new Date();
    inicio = inicio.getTime();
	
    $(window).unload(function(){
    fim = new Date;
    fim = fim.getTime();
    $.ajax({
    url: 'http://127.0.0.1/time.php',
    data: {'time': fim - inicio},
    success: function(i){$('#demo').html(i);}
    });

    });
});
</script>
</head>

<body>
<div id="demo"></div>

</body>
</html>

time.php

<?php
# converter o tempo para um formato legivel
function converter($tempo)
{
    $hora = 0;
    $tempo = $tempo / 1000;
    $ms = str_replace('0.', '', $tempo - floor($tempo));
    if($tempo > 3600)
    {
        $hora = floor($tempo / 3600);
    }
    $tempo = $tempo % 3600;
    $out = str_pad($hora, 2, '0', STR_PAD_LEFT) . gmdate(':i:s', $tempo) . ($ms ? ".$ms" : '');
    return $out;
}

if(isset($_GET['time'])){
    $file = fopen('time.txt', 'w');
    if($file){
        fwrite($file, converter($_GET['time']));
        fclose($file);
    }
}
?>

and finally:

% blank%.

Does anyone know what's wrong? I need a lot to solve this problem.

    
asked by anonymous 25.12.2016 / 22:31

1 answer

0

Making an AJAX request on a unload event does not guarantee that it will be completed. I'm not sure if this depends on the connection being fast enough or if the browser cancels the request.

But there is a solution!

If async: false is specified in the request, the tab will only be closed or it will move to the next page once it is finished.

jQuery(window).unload(function () {
    jQuery.ajax({
        url: 'http://127.0.0.1/time.php',
        async: false,
        data: { time: fim - inicio }
    });
});
    
26.12.2016 / 00:33