vdegenne
vdegenne

Reputation: 13308

onbeforeunload doesn't seem to always be trigerred

Here's a minimum example -

index.php

<?php
$count = file_get_contents("count.txt") + 0;
file_put_contents("$count.txt [loaded]", '');
file_put_contents("count.txt", $count + 1);
?>

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <script src="jquery-1.10.2.min.js"></script>
</head>
<body>
<main>
    <p> hi there </p>
</main>

<script type="text/javascript">
var id = "<?php echo $count; ?>";
</script>

<script src="script.js"></script>
</body>
</html>

script.js

$(document).ready(function () 
{
$(window).bind('beforeunload', function () {
    $.post("unloader.php", { id : id });
});

});

unloader.php

<?php
file_put_contents("$_POST[id] [unloaded]", '');

When I open the webpage, a file is created with the count number as its name. When I close the tab jquery requests unloader.php which is just a standalone script that creates a file with the count number as its name too.

Sometimes it works, sometimes it doesn't. I mean the opening file is always created. But sometimes the file which has to be created on closing is not made. Any idea where the issue occured ?

Upvotes: 0

Views: 220

Answers (1)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324820

You can't (reliably) make AJAX calls when unloading the page. Because it's being unloaded, anything still in progress will be dropped.

If the browser's fast enough with the AJAX call (or the server's slow enough in responding to the new page load) then you should see a result, but it is not at all reliable.

Upvotes: 2

Related Questions