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>