I am trying to block the unload event for a page until I get a response from the server for an async json call initiated by the client.
To make it clear, the scenario is the following: I need to save the user changes into a database when they close the browser. While doing so, I will show a small div and hide it when we’re done (hiding it doesn’t matter, the page will already be gone!)
In code, this is pretty much what I am trying to do.
PS: I don’t want to use alert()
window.onbeforeunload = function () {
var requestURL = "../foo/Save";
$("#dvMsg").show();
$.getJSON(
requestURL,
{
changeId: 1,
userId: 1
},
function (data) {
// hide the dvMsg
$("#dvMsg").show();
// page should be safe to unload
});
};
The problem is the nature of the async call i.e. it will not block and the page will be unloaded before we get the response.
Any ideas?
Thanks!
I don’t think this can be done at all if the event is asynchronous.
Why not make it synchronous? That’s probably your best chance to get it through.