I see you posted it in the AJAX forum, so you know the answer : send an [tt]XMLHttpRequest[/tt] call to notify the server.
That is the good old portable way. But now there is the Beacon API's [tt]sendBeacon[/tt] Method, specially designed for this situation. Less portable for now ( see Can I use... beacon ), but more reliable.
Feherke,
Thanks, but how is sendBeacon used ? I tried the following to store the time the page is unloaded but it didn't
seem to run the alert.php to change alert.txt.
<html>
<head>
<title>alert.htm</title>
</head>
<body>
alert.htm
<script type="text/javascript">
window.addEventListener('unload', logData(), false);
function logData()
{
navigator.sendBeacon("alert.php", nowhhmm() );
}
function nowhhmm() //with leading zero
{
var now = new Date();
var hournow = now.getHours();
var minutenow = now.getMinutes();
var hhmm = hournow*100 + minutenow;
hhmm = ("0" + hhmm).slice(-4);
return hhmm;
}
</script>
</body>
</html>
<?php
//alert.php
$data = $HTTP_RAW_POST_DATA;
$file = 'alert.txt';// Open the file to get existing content
$prev = file_get_contents($file);
$total = $data . $prev . "\n";
file_put_contents($file, $total);
////fclose($file); //not needed ?
exit();
?>
Merry Christmas.
It works for me in FireFox 50.1.0, just the beacon is sent in wrong moment, because you call logData() when setting up the event handler - you should reference it instead :
Code:
window[teal].[/teal][COLOR=orange]addEventListener[/color][teal]([/teal][i][green]'unload'[/green][/i][teal],[/teal] logData[teal],[/teal] [b]false[/b][teal]);[/teal]
[gray]// no () here --^[/gray]
Regarding your PHP code, do you realize you always put the newline at the end of file, not between previous and new data ? ( Also no idea why you need the times logged in reverse order. ) Anyway, first of all, please check whether the web server's user has permission to write in that directory. Check your web server's error log, probably you will find something like this :
/var/log/apache2/error.log said:
[Sat Dec 24 15:42:55.416260 2016] [:error] [pid 7654] [client 127.0.0.1:55198] PHP Warning: file_get_contents(alert.txt): failed to open stream: No such file or directory in /var/
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.