0

I have this so far

window.addEventListener("beforeunload", function(e){
      $.post('insert.php', {'postmessage':'CALL bor.update_records_exit(\'' + authUser + '\');'}, function(data) {
            e.returnValue = null;
            return null;
      })
      .fail(function(response) {
            alert('Error: ' + response.responseText);
      });
});

This is working but not reliably. Sometimes the request is sent, sometimes it isn't and I don't understand why.

I know that it has something to do with the synchronicity of the request. I tried using .ajax() instead and setting async property to false, but then i realized that async:false has been depracated.

All i need to do is send a final insert query when the user closes the browser or the tab... Please help.

1 Answers1

0

You're correct that async: false is deprecated, however you have no choice than to use it when making an AJAX request in the beforeunload event. It just about the only legitimate use for it, in fact.

This is because you need to wait for the request to complete before the browser can be allowed to close. The behaviour you see now, where some requests fail, is for that reason; the browser closes too early in the request pipeline.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Thank you for your response. But if it's been depracated, how can i use it? And is there any way for me to make the browser wait until the POST request is completed before closing? – Youni Halloumi Nov 15 '20 at 16:47
  • Deprecated doesn't mean that you can't use it. It means that it's not good practice in most cases, however here you have no choice. *'is there any way for me to make the browser wait until the POST request is completed before closing?'* currently the only way is to use `async: false`. If you don't want to use that solution then you will need to restructure your page so that you do not have to update the server when the page is unloaded. – Rory McCrossan Nov 15 '20 at 17:03