Runnig a mysql query using ajax or sendBeacon from window.onbeforeunload

I need to run a query when the page is closed by the user. Apparently; window.onbeforeunload us the correct event. In fact I can see that it triggers.

Now, the problem is that for some reason (unknown to me) when issuing an AJAX request like this AJAX does not run:

window.onbeforeunload  = function(e) { 

    jQuery.ajax({
      type: 'POST',
      url: 'release_all_holds.php',
      datatype: 'json',
             data: { SEATS: JSON.stringify(selectedSeats),
                    },
      async: false,
    });     

}

It also does not work when using navigator.sendBeacon like this:


window.onbeforeunload = function(e) {
    
    var headers = {type: 'application/json'};
    var blob = new Blob(JSON.stringify(selectedSeats), headers);
    navigator.sendBeacon('release_all_holds.php', blob);
};

I know it did not run because I check the table in mysql and see it has not updated.

  • After you initiate the AJAX request, the page unloads. This cancels any AJAX requests that were initiated.

    – 




  • OK. So what is a good way to delay the unload. I tried and it did not work.

    – 

  • Actually, sendBeacon() is supposed to be the workaround, according to stackoverflow.com/a/60770031/1491895. Are you sure the PHP code is able to process JSON data rather than using $_POST?

    – 

  • See stackoverflow.com/questions/9597052/… for the changes you need to make to the PHP script.

    – 

  • That answer also recommends using unload rather than beforeunload. The purpose of beforeunload is to ask the user for confirmation on trying to leave the page.

    – 

Has anyone here actually been successful doing this. Maybe provide code I can use.

Leave a Comment