I need to clear the session variables when the tab is closed but I could not find any solutions so far. The closest I have got is by using the "onbeforeunload" function is javascript.
<body onbeforeunload='destroySession()'>
<!--Codes for the site includeing php scripts-->
</body>
<script type='text/javascript'>
function destroySession(){
$.ajax({
url: "destroySession.php"
});
}
<script>
The problem is the function is called every time a new link is clicked, refreshed or even if a form is submitted. Is there a better way to destroy session variables on closing a tab or am I doing something wrong? Please help.
Yep you can do it,
There is no secure way of handling what you are looking for. onbeforunload event executes every time you leave the page. (I had similar problem like this yesterday for one of my projects). The closest you can get is to control how the users leave the page.
See this link posted by lan in some of the comments. And check the answer by Daniel Melo That is as close you can get with the solution from this problem.
I also found this link but its basically the extraction of the answers given in stackoverflow.
Hope this helps.
Unfortunately, there is no way to prevent page refresh (caused by form submit or any other navigation) from calling "onbeforeunload".