1

I am trying to create a website that has to execute a specific server side task at the time the user exits the web page.

After a lot of research and experimenting what I managed is not working. First, I tried to handle the exit event. I use the "beforeunload" event on jquery to handle it. When the user tries to close or refresh the specific webpage I need to execute some php code.

I need to send a variable (a name) to the php file. There is no response from it. It just executes a task with the name. Here is the code that I tried:

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
    $(window).on("beforeunload", function() {
        $.ajax({
            type: "POST",
            url: "unload.php?name=SOME_VARIABLE",
            success: function(data) {}
    });
});
</script>

The problem is that it is not working. No errors appear on the element inspector. The "unload" php file is working as expected. In fact, when accessed directly through its address, it executes the desired task properly.

I have no previous contact with ajax nor do I master jquery. If there is any better way to achieve this please feel free to tell me.

Thank you in advance.

Nick
  • 241
  • 1
  • 2
  • 10

2 Answers2

1

Try sending a beacon, but it supports is limited see this

window.addEventListener("beforeunload", doSomething, false);

function doSomething() {
  navigator.sendBeacon("unload.php?name=SOME_VARIABLE", data); // modify this to befit your need.
}
Morlo Mbakop
  • 3,518
  • 20
  • 21
1

You have to use async: false in AJAX requests sent onbeforeunload, otherwise the tab is destroyed before the response can be handled. Try this:

$(window).on("beforeunload", function() {
  $.ajax({
    url: "unload.php?name=SOME_VARIABLE",
    type: "POST",
    async: false,
    success: function(data) {
      // your code here...
    }
  });
});

Note that this is the only situation in which synchronous AJAX requests should ever be used. In all other cases they should be sent asynchronously.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339