-1

I am creating a web app to save data to MySQL database. now I need to save data when the browser closes. I used the ajax function to call my PHP web services. I used onunload event to detect the browser close event. My problem is when the browser close it fire the onunload event but does not wait until the ajax function success. Because of that data is not saved to the database. When I put debug point on the onunload function it is working fine and save all the data to the database.

This is what I tried.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<h1>Testing data save on close event</h1>
    
</body>
</html>
<script>
window.onunload = function(e) {
        console.log("The Window is closing!");
        saveDataOnClose();
};
    
function saveDataOnClose(){
  url = URL+"savedata.php";
  
  var client = [{firstName: 'John', lastName: 'doe', EmailAddress: 'jhon@gmail.com'}];

  var jObj = JSON.stringify(client);

    $.ajax({
      url: url,
      type: "POST",
      data: {
          "Client": jObj,
      },
      success: function (result) {

          var Id = result;
          localStorage.setItem("result", Id);          
      },
      error: function (xhr, errorType, exception) {
          console.log("Store data on remote database", "Storing data on the remote database failed, " + xhr.statusText + " " + xhr.status + new Error().stack, false);
      }
    });
}
</script>
Sidath
  • 379
  • 1
  • 9
  • 25

2 Answers2

0

The window.onunload function is an special function, so actually asynchron code can be executed, but will be killed by the browser, when the tab has been closed which happens immediately.

A similar question has been answered here. The solution there could be with service workers, which handles the data in the background, even if your website is not opened.

But, what you could also do is to store the data to the localStorage object temporarily, which handles the data synchronous.

As soon as your user comes back to your website on the same device, you can check if there is any unsaved changes and sync it with your backend.

Julian Schmuckli
  • 3,681
  • 11
  • 37
  • 64
  • Thank you so much. Actually, I need to save data when the browser closes. is there any other way to do it? – Sidath Nov 15 '21 at 08:23
  • Well, then you need to register a service worker and [post the data to it](https://stackoverflow.com/a/51729414/5508719), which can then send an AJAX request to the server. The big advantage is then, that it can handle the data in the background. – Julian Schmuckli Nov 15 '21 at 08:29
  • ok. thank you. I'll try this. – Sidath Nov 15 '21 at 08:44
0

In your case, consider using the onbeforeunload event. What this event does is that it shows a confirmation box to the user when he is about to close the tab or reload the page or tries to move away from the current page.

<html>
<body onbeforeunload="return myFunction()">

<a href="https://www.google.com/">Click here to go to Google.com</a>
    
<script>

function myFunction() {
  return "Return anything here.....";
}
</script>

</body>
</html>
Dharman
  • 30,962
  • 25
  • 85
  • 135
S M
  • 111
  • 11
  • onbeforeunload event fire when navigating to another page. It's not applicable in mycase. – Sidath Nov 15 '21 at 08:46
  • Yes it does fire when navigating to another page, but it also fires when you attempt to close the browser. I did get a confirmation box from the browser when I tried to close the browser using 'onbeforeunload'. – S M Nov 15 '21 at 09:22
  • I need only for browser close. – Sidath Nov 15 '21 at 09:24
  • As I mentioned above, it works for all the scenarios including 'browser close'. – S M Nov 15 '21 at 09:25