The problem is that you're issuing an asynchronous call to the server. The
beforeunload
event handler returns before the AJAX call has completed, and the browser continues with unloading the page.
According to
the documentation[
^], you can specify
async:false
in the settings passed to
$.ajax(...)
, which might solve the problem:
window.onbeforeunload = function (evt) {
var id1 = document.getElementById("<%= hdScenario1.ClientID %>").value;
var id_1 = '';
$.ajax({
type: "POST",
url: "scenarioAdd.aspx/CheckUpdateScenario",
data: '{scenarioId: ' + id1 + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (response) {
id_1 = response.d;
},
failure: function (response) {
alert(response.d + " f");
id_1 = 0;
},
error: function (response) {
alert(response.d + " e");
id_1 = 0;
}
});
if (id_1 == 0) {
var message = 'Save it before you close.';
if (typeof evt == 'undefined') {
evt = window.event;
}
if (evt) {
evt.returnValue = message;
}
return message;
}
};