Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if a user leaves a page in PHP

Tags:

javascript

There is this function which i want to execute in case the user leaves a particular page. This function will basically change all of the data within a certain column in my database. So in case the user leaves this page, i want this function to be performed by the system. Is there a way to detect if the user already left the page.

Thanks!

like image 247
Mike Avatar asked Jun 14 '12 03:06

Mike


3 Answers

With 100% reliability, no, it's not possible. Since leaving a particular page is a client-side operation, you have 0 control over what the client does. You can register an onbeforeunload handler via Javascript and hope that the client browser supports it. But again, support for this isn't universal.

like image 91
Marc B Avatar answered Sep 23 '22 12:09

Marc B


You can't do this in php but you could use the javascript function onbeforeunload, here an example

<script type="text/javascript">
  window.onbeforeunload = confirmExit;
  function confirmExit()
  {
    return "You have attempted to leave this page.  If you have made any changes to the fields without clicking the Save button, your changes will be lost.  Are you sure you want to exit this page?";
  }
</script>
like image 39
Sebr Avatar answered Sep 22 '22 12:09

Sebr


You can't do that using PHP since it's a server-side language. You will need to use JavaScript.

like image 24
Soufiane Hassou Avatar answered Sep 21 '22 12:09

Soufiane Hassou