JavaScript sometimes prevents server event from firing with asp.net - javascript

I have what I thought was a pretty straightforward javascript issue, but I'm starting to go nuts trying to figure out my problem.
I have a slow page, and it was possible for users to click submit, then click another button while waiting on the page to load, it was creating issues. I thought I could display a please wait message and disable the submit button on click. Below is the function, I am using asp.net 3.5 so there's a name mangling issue, because of this I was using a getElemenetsByName and scanning for the right items (not awesome but it seems to work). When I run this, the button becomes disabled, but then the page just sits there, the server never gets called. I tried in firefox and I didn't see any errors in firebug, but when I set a breakpointon the server, the server def does not get called. I tried returning true in case there was an output expected, but nada. When I commend out the content of processing(){ // stuff } then it works fine, so something in there seems to be killing me.
function processing() {
var pleaseWaitID = "lblPleaseWait";
var submitBtnName = "btnSubmit";
var submitControl = document.getElementsByTagName('input');
var pleaseWaitlbls = document.getElementsByName(pleaseWaitID);
for (pleaseWait in pleaseWaitlbls) {
if (pleaseWaitlbls[pleaseWait].style != null) {
pleaseWaitlbls[pleaseWait].style.visibility="visible";
}
}
for (submitButton in submitControl) {
if (submitControl[submitButton].name != null) {
if (submitControl[submitButton].name.search(submitBtnName) != -1) {
submitControl[submitButton].disabled = "disabled";
}
}
}
return true;
}
.....
asp:Button ID="btnSubmit" name="btnSubmit" SkinID="MainAction" runat="server" Text="Submit" OnClientClick = "javascript:processing();"
OnClick="btnSubmit_Click" meta:resourcekey="btnSubmitResource1"
Any ideas on what I've screwed up here?
Thanks you for your time.

Asp.net Custom user control button. How to stop multiple clicks by user
I had the same type of problem this may or may not help.

Related

How to handle Unsaved Changes in LWC component?

I am trying to implement unsaved changes functionality in the LWC component. Tried various approaches including using javascript & jquery and tried to fire it onbeforeunload but things don't seem to work. The same works on the HTML page but not as expected in LWC.
I tried using the below code in a util class:
const handleUnsavedChangesValidation = (hasModifiedData, updateClicked) => {
console.log('>>>:::INN::hasModifiedData::', hasModifiedData);
console.log('>>>:::INN::updateClicked::', updateClicked);
var modified = hasModifiedData && !updateClicked ? true : false;
if(modified) {
addEventListener("beforeunload", (evt) => {
const unsaved_changes_warning = "Changes you made may not be saved.";
evt.returnValue = unsaved_changes_warning;
return unsaved_changes_warning;
});
}
else
{
removeEventListener("beforeunload", () => {
return true;
});
}
}
On any changes to the input field I tried calling the following method with these params :
handleUnsavedChangesValidation(true, false)
On save button click I tried calling this
handleUnsavedChangesValidation(true, true);
On trying the above, it works partially fine:
On load -> alert is not displayed (as expected)
On input updates -> If refresh is pressed (alert displays - expected)
On input updates -> If the tab is clicked is pressed (alert displays - expected)
On input updates -> If browser back button is clicked (it fails to display alert)
On input updates -> If update button is clicked (it still displays alert stating unsaved changes and then on click of Ok it saves. This is also not expected. Alert should not display here)
Post save -> On page refresh -> Now alert displays which is also not expected.
Once again if I click refresh it does not display an alert.
I am looped and tried finding many ways to handle this via static resource and other ways but could not do anything here. Tried to pass blank to the return value of unload yet no result. Tried passing return true as well as return false. Yet it seems to display an alert when we click on save.
Anyone knows any alternative or can someone please help me out here. I am looking for a solution that works for LWC implementation and not just html javascript.
Please help geeks. Any help is highly appreciated.
Thanks in advance, stay safe.
Regards,
Rajesh

Page failing to redirect and clearing URL parameters

I have a webpage that makes a POST request to a PHP script. Depending on the result of the request, the onclick event for a button sets a redirect to one of two pages.
<button id="button" type="submit">Proceed</button>
...
$.post('script.php', {
key: value
}, function(result) {
if (result != null) {
document.getElementById("button").onclick = function() {
window.top.location.href = "https://example.com/page?otherkey=othervalue";
}
} else {
document.getElementById("button").onclick = function() {
window.top.location.href = "https://example.com/otherpage?otherkey=othervalue";
};
}
});
This works fine on desktop browsers, but on Safari on iOS (specifically tested on iOS 10.3.2) upon clicking the button, the page refreshes and doesn't redirect to the correct site. In addition, it clears any URL parameters that were previously there. So for example if the page with the button is example.com/page?key=value, the page will refresh and become example.com/page?#_=_. I've tried debugging and checking a Javascript console, but it doesn't say anything.
The redirect is a page in my own domain, though the page with the button is integrated into a Facebook app page, if that's relevant.
Also, if I construct the URL on my own and try to go to it normally, it loads fine. I don't know what could cause this, so I'm not sure if there's any other relevant information worth posting, but I can say more if necessary.
Safari does not deal well with return false being done in the function, and especially with no return at all. I would include a onsubmit="return function();" in the html element, which I'm guessing is a form. You also attach this to the submit() event listener via $('[the form ID]').submit(function(){ do something here; return false;});
I was right that I suppose I didn't supply enough detail, but it seems that because the button in question was inside a <form> tag and acting as a submit button, that was messing it up. To solve the issue, I removed the form (since I was not submitting any data anywhere, just using the button to redirect the page) and it solved the issue. Now it works on desktop and mobile browsers.

confirm() cancel button no longer working in IE11

I have an asp.net 4 site that I am using javascript's confirm() method before a user deletes an object from the database as a client based confirmation. With IE6-10, Firefox, Chrome, and Safari this works well. I click on cancel and it stops the page loading. However I been having problems using this on a usercontrol with IE11.
The usercontrol loads a datagrid which has an link button that gets the server to call a delete stored procedure.
With IE11, the Confirm popup opens, but if I click the cancel button or x on the window does not stop the page posting and calling the delete command in the server. I tried everything I can think off, but it just always passes and reads the page as valid.
In the code behind of the ItemDataBound we have this...
DeleteButton.CommandArgument = ac.ID.ToString(); //set the id so we know what to delete
DeleteButton.Attributes.Add("onclick", "Sure(event)");
This attaches the javascript to the image button.
Then in the file that contains the javascript we have the following code...
function Sure(evt){
var ans = confirm("Are you sure you want to delete? \n\nPress OK to continue or Cancel to stop.");
if(!ans){
var e = (window.event)? window.event:evt;
e.returnValue = false;
return false;
}
}
Debugging, it is setting the values to false and returning them when I press the cancel button, but this isn't stopping the postback like every other browser does. It goes straight to the call for the database to delete it.
Any idea why IE11 wouldn't stop the postback after confirm was cancelled?
If I'm hearing you right, don't you mean...?
"onclick", "return Sure(event)"
...
function Sure(evt){
var ans = confirm("Are you sure you want to delete? \n\nPress OK to continue or Cancel to stop.");
if(!ans){
var e = (window.event)? window.event:evt;
e.returnValue = false;
return false;
} else {
return ans;
}
}
From my understanding your script shouldn't work anywhere, even IE11. If you don't "return" the value of the function, you are just executing the function and ignoring the fact the confirm dialog returns "false".

onbeforeunload and asp:Update Panel in Safari and FireFox

I am working on a asp.net (framework 4) that has a requirement for the user to be notified if they are trying to leave the page without saving changes. Well I found a solution by calling the onbeforeunload function via JavaScript. Works great in IE but not in Firefox, Safari or Chrome.
Now here is where the problem comes in. I’m using AJAX postbacks and if the user is prompted to save the changes before leaving the page, any controls inside of the update panel no longer will postback to the server. For example, if a press the save button that is inside of the update panel, nothing happens.
Here are some code snippets
javascript:
window.onbeforeunload = function (e) {
if (doBeforeUnload() == true) {
var ev = e || window.event;
// For IE and Firefox prior to version 4
if (ev) {
ev.returnValue = "You have modified the data entry fields since the last time it was saved. If you leave this page, " +
"any changes will be lost. To save these changes, click Cancel to return to the page, and then Save the data.";
}
// For Safari
return "You have modified the data entry fields since the last time it was saved. If you leave this page, " +
"any changes will be lost. To save these changes, click Cancel to return to the page, and then Save the data.";
}
}
ASP.NET:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" >
<ContentTemplate>
<%--no controls inside of this panel will postback to server if user clicks the “Stay on Page” button--%>
</ContentTemplate>
</asp:UpdatePanel>
Seems to be plenty of posts on the net but no solutions. Any ides besides not using async postbacks?
I came across this question when I was searching for the similar issue. I was able to solve this by doing the following:
var doOnBeforeUnloadCheck = true; // global to set in link button
window.onbeforeunload = function (e) {
if (doOnBeforeUnloadCheck && doBeforeUnload()) {
// do stuff
}
// Make sure to always re-enable check to ensure the event will still trigger
// where not specified to disable event.
doOnBeforeUnloadCheck = true;
}
In a LinkButton you just make sure to set the global to false before running any other javascript or doing the postback:
<asp:LinkButton ID="yourButton" runat="server"
OnClientClick="doOnBeforeUnloadCheck = false;" OnClick="yourButton_Click" />
I came across this solution with help from the following link:
http://www.jimandkatrin.com/CodeBlog/post/LinkButton-UpdatePanel-onbeforeunload.aspx
I found this question before I found my answer so if anyone else has the same issue this might save them some time. Hope that helps.

Stop ImageButton OnCommand postback using javascript in asp.net 4.0 (Internet Explorer)

It looks like the Internet Explorer demon has struck again, and I cannot seem to figure this one out:
I have an ImageButton using OnCommand to delete a specific entry from my database. I however have implemented it so that the user will first confirm that they want to delete a specific item.
Here is the code for my ImageButton
<asp:ImageButton runat="server" ID="imgDelete" ImageUrl="~/Controls/TaskDetails/Images/delete.png" OnCommand="Tag_DeleteCommand" Visible='<%# CanDelete %>' OnClientClick="javascript:confirmDialog(this, 'Remove Tag','Are you sure you want to remove this tag?', 1); return false;"
CommandArgument='<%# Eval("TagID") %>' />
And here is my ConfirmDialog function
function confirmDialog(sender, title, message, type) {
//type entities
//1 = warning
//2 = error
//3 = success
//4 = Information
var sender = $(sender);
$("#message_dialog_inner_text").html(message);
$("#message_dialog_message_container").dialog({
modal: true,
title: title,
zIndex: 10003,
dialogClass: (type > 0) ? "message_dialog_type_" + type : "",
position: 'center',
buttons: {
"OK": function () {
//the yes option was selected, we now disable the onclientclick event, and fire the click event.
$(this).dialog("close");
if (sender.hasAttr("href")) {
window.location = sender.attr('href');
} else {
sender.removeAttr("onclick");
sender.trigger("click");
}
},
"Cancel": function () { $(this).dialog("close"); }
}
});
return false;
}
This works fine in Chrome, FF, Safari, but IE is just ignoring it and doing the postback. I have even changed my OnClientClick to "return false;" and it seems to have no impact on the button posting back. I have also changed it from an ImageButton to just a Button, to no avail. I am assuming it has something to do with the OnCommand event, but right I am at a loss! I have implemented this througout a pretty huge application, so I would like to manage the scope of the change. If anyone has some input, it would be greatly appreciated!
EDIT
OK, let me also just stress, I don't want it to post back, and even if I just have OnClientClick="return false;" the command button is still posting back (not what you would expect).
Here is the rendered markup from my ImageButton control
<input type="image" name="ctl00$body$pnlContentRight$pnlCurrentTaskDetails$repTags$ctl00$tagItem$imgDelete" id="ctl00_body_pnlContentRight_pnlCurrentTaskDetails_repTags_ctl00_tagItem_imgDelete" src="Controls/TaskDetails/Images/delete.png" onclick="javascript:confirmDialog(this, 'Remove Tag','Are you sure you want to remove this tag?', 1); return false;" style="border-width:0px;">
This isn't a resolution to your specific issue, but it's a workaround you may want to consider (I've used it in a couple of places):
Make your "delete" button a simple image, not a postback button.
Give it an OnClientClick which calls a local javascript function (passing the relevant data - at a minimum, the ID of the item to be deleted).
That local JS function loads the relevant data into a hidden var (so it can be accessed in your code-behind), and opens the jQuery confirm dialog.
That dialog is configured with NO jquery-dialog buttons. Instead, the launched DIV contains two asp:Buttons: ok and cancel. The cancel button simply closes the jQuery dialog. The OK button is a normal postback button with a server-side OnClick function.
Thus, the page is only posted-back if the user clicks the OK button on the confirm dialog. The confirm-dialog-event function knows which item to delete because that item's ID is in the hidden field.
This is probably not the "right" way to implement this behavior (from an ASP.NET purist standpoint). However, as workarounds go, I don't think it's too painfully kuldgey. And in my experience, it seems to work across all browsers (assuming they have JS enabled, of course). HTH.
You're OnClientClick is always returning false, which means that the event will never be executed. Try returning the input from the confirm like this:
OnClientClick="return confirmDialog(...);"
You will need to make sure that there is a way to return true from the confirmDialog function too. It looks like that function always returns false too.
I'm not very familiar with the jQuery UI dialog, but in concept it should work like this:
buttons: {
"OK": function () { return true; }, //perform a postback and execute command
"Cancel": function () { return false; } //abort postback and do nothing
}

Categories