I am currently trying to send a request when an user closes the page. I am using the onbeforeunload
event.
The event triggers when the tab is closed or the page is refreshed. My event looks as follows:
window.onbeforeunload = function () {
$.ajax({ //jQuery
type: "POST",
url: "offline.php",
data: {
logout: 'false'
}
});
};
offline.php (this is not the complete script):
...
unset($_SESSION["onpage"];
if ($_POST['logout'] == "false") {
sleep(3);
if (isset($_SESSION["onpage"]) || !empty($_SESSION["onpage"])) die();
}
...
When a user closes the page, script unsets a session that is set on the page of the chat. After three seconds, the script should check if the user has returned but checking the onpage
session. However, the problem comes in when I hit the refresh button. On refresh, the page does not load because the three seconds have completed. This is causing my whole system to be ruined.
I have tried adding ignore_user_abort(true);
but it did not solve my issue. Is there any other way of getting this to work?
Side Note: This is for a chat. When a user closes the page, it should notify the other users on the chat with a "The user has left" message. This should not be displayed on refresh. When a user comes back to the page, it should notify the other users that the user has returned with a "The user has entered" message.