0

When a user navigates away from a particular webpage, I need to update the database via PHP code, preferably without a popup window. The code below opens a "Confirm Navigation" popup, and works if I respond "Leave this Page", by navigating away and running the code on "mypage". However, if I respond "Stay on this Page" it will still run the code on "mypage", which I don't want to happen.

<script type="text/javascript">
window.onbeforeunload = CallPHP;
function CallPHP () {
    var a = new XMLHttpRequest();
    a.open("GET","https://mydomain.com/mypage",true);
    a.send();
    return "Thank you.";
}
</script>

I don't know how to call the PHP file directly, and I don't know how to avoid the popup and just let the user navigate away. Any help greatly appreciated.

2 Answers2

0

You probably don't want to rely on that, cause unload is massively unsupported in a lot of browser versions. Some won't even let you do anything except outputting a standard alert box. So there's not much you can do about it as far as I know.

Not the answer your looking for, I know. But I had the same issue and tried a lot. Eventually I went with a blur on each input.

Matt
  • 1,081
  • 15
  • 27
0

To avoid the pop-up, just don't return anything. When nothing is returned, no pop-up is shown, so all you would need to do is get rid of the line:

return "Thank you.";

It was mentioned before that it isn't necessarily reliable, and I'd like to add to that caution. Onbeforeunload is fantastic for pausing a leave-page event as well as giving the option to execute code during that time. The problem is if you get rid of the pop-up, it's possible that not all of the code will have time to be executed. I've never had a problem using short code, for instance logging out a user. In reality, you should be fine but I figured you should know about the possibilities.

Brian
  • 529
  • 2
  • 7
  • 17