php – Problem catching access time

Question:

I'm trying to get the time the internet user spent 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>-->
<script src="jquery-3.1.1.js"></script>
<link href="style.css" 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 time.txt .

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

Answer:

Making an AJAX request in an unload event is not guaranteed to 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 close or move to the next page once it has finished.

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