I am using window.onbeforeunload
and window.onunload
to confirm with user if he really wants to navigate away from a Page. I am calling a Page Method on Server Side to do some database book keeping when user selects 'Leave' option on the dialog using jquery.ajax() method.
But my jquery.ajax()
to the Page method returns error. It works as expected when calling from other javascript functions.
here are the snippets I am using.
In the Page.aspx
function confirmExit() {
console.log('In ConfirmExit function unlock='+unlock+'needsave='+needSave);
timeout = setTimeout(function() {
}, 1000);
return "You have pending changes on this request";
}
function unloadPage(){
console.log('In Unload Page function unlock= '+unlock+'needsave= '+needSave);
if (needSave && unlock) {
UnlockRequest(null);
return "You have pending changes on this request";
}
clearTimeout(timeout);
}
Also, I am setting
window.onbeforeunload = confirmExit;
window.onunload = unloadPage;
in the Page.aspx. Here's my ajax call to the Server in Unlock Method
dataString = "{'reqID' :'" + selectedVal + "'}";
var url = "Page.aspx/UnLockRequest";
console.log('Calling Unlock Request from Unlock Method');
jQuery.ajax({
type: 'POST',
url: url,
data: dataString,
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: 'false',
success: function () {
var r = $("#MainContent_btnSubmit")
r.prop('disabled', true);
var r = $("#MainContent_releaseLockButton")
r.prop('disabled', true);
r = $("#MainContent_Button2")
r.prop('disabled', true);
if ($('#RequestLockedDiv').get(0) !== null)
$('#RequestLockedDiv').get(0).setAttribute("style", "display:none;");
needSave = unlock = false;
$(document).stopIdleTimeoutPlugin();
//window.location.reload(false);
}
});
The Server Method in Page.aspx.cs
[WebMethod]
public static void UnLockRequest(string reqID)
{
int requestId = 0;
if (int.TryParse(reqID, out requestId))
{
UserInfo lockUser = BLRequest.GetLockerInformationByRequestId(requestId);
UserInfo currentUser = HttpContext.Current.Session["CurrentUser"] as UserInfo;
if (lockUser != null && currentUser != null && currentUser.IDSID.ToUpper().Equals(lockUser.ID.ToUpper()))
{
BLRequest.UpdateRequestLockStatus(requestId, 0);
}
}
}
I can't see this server request sent neither in Network tab of browser nor in fiddler. BTW I am using Chrome for testing and ASP.NET 4.0. what am I missing.