Greetings in advance, I am diving into the world of JavaScript for the first time. The code snippets provided below have been crafted after seeking guidance from various sources.
My aim is to utilize a webmethod that detects if a page has undergone modifications and returns a boolean value:
<script type="text/javascript">
function OnConfirm() {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "UserManagement.aspx/IsDirty",
dataType: "json",
data: '{}',
success: function OnDirtySuccess(result) {
if (result.d.toString() == "true") {
return confirm("You have unsaved changes, select OK to discard these changes without saving.");
}
else {
return false;
}
return true;
},
failure: function (response) {
return true;
}
});
}
</script>
A button triggers the execution of this script:
<asp:Button ID="btnAddNewUser" CausesValidation="false" runat="server" Text="Add New User" OnClick="btnAddNewUser_Click" OnClientClick="return OnConfirm();" Width="140px" />
The method call is functioning correctly as I only receive the confirmation dialog when the current user has been modified. However, my concern arises when clicking 'cancel' as the btnAddNewUser_Click event still gets triggered.
I attempted an alternate approach based on another question, but encountered issues:
<script type="text/javascript">
function OnConfirm() {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "UserManagement.aspx/IsDirty",
dataType: "json",
data: '{}',
success: function OnDirtySuccess(result) {
if (result.d.toString() == "true") {
if (!confirm("You have unsaved changes, select OK to discard these changes without saving."))
return false;
//return confirm("You have unsaved changes, select OK to discard these changes without saving.");
}
else {
return false;
}
return true;
},
failure: function (response) {
return true;
}
});
}
</script>
<asp:Button ID="btnAddNewUser" CausesValidation="false" runat="server" Text="Add New User" OnClick="btnAddNewUser_Click" OnClientClick="if (! OnConfirm()) return false;" Width="140px" />
In this revised snippet, I adjusted the OnClientClick to `if (! OnConfirm()) return false;` while also trying both versions of the confirm action within OnConfirm(). Unfortunately, even after choosing 'cancel' on the confirm dialog, the OnClick event persists.
A simplified test was conducted by altering the OnClientClick function to:
<script type="text/javascript">
function OnConfirm() {
return confirm('Test ok/cancel?');
}
</script>
Here, the ok/cancel functionality of the confirmation dialog worked seamlessly.
What could be causing the issue with my OnConfirm function?