Apologies beforehand, this is my first time coding using javascript. All of this I have written based off of other questions I found on here.
I have a call to a webmethod that checks whether a page is dirty and returns a boolean:
<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>
I have a button that calls the 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 working correctly, I only see the confirm dialog when the current user has been modified. My issue is when I click 'cancel' the event for btnAddNewUser_Click is still firing.
A different approach based on another question posted here, that did not work for me:
<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" />
Here, I modified the OnClientClick to if (! OnConfirm()) return false; and I tried using both versions of the confirm code inside OnConfirm(). However, when the confirm dialog pops up and I hit cancel, the OnClick event still fires.
I've tried changing the OnClientClick function to (just to simplify the code and test):
<script type="text/javascript">
function OnConfirm() {
return confirm('Test ok/cancel?');
}
</script>
and the Ok/Cancel of the confirmation dialog is working properly.
What am I missing with my OnConfirm function?