pop up messages once aspx - javascript

currently I am facing a problem with pop up msgs.
The messages should prompt out first time click on a NEXT button.
when we go to the next pages and back to the previous pages, and click on the same NEXT button, the pop up msgs should not appear.
how can i fix this?
This is button code
<asp:Button ID="Button1" runat="server" onclick="Button1_Click1" Text="Next" Width="100px" />
This is the function() for my clickedOnce
<script type="text/javascript">
window.document.onload = function()
{
var clickedOnce = false;
Button1.Button1_Click1 = function ()
{
if(!confirm('Please make sure the employee particulars and reporting line details are correct before save. \nClick OK to save and continue if all details are correct.\nClick Cancel and contact HR Admin if details appear is not up to date.'))return false;
clickedOnce = true;
}
}
</script>
Thank you. your kindness and help much appreciated.

Well, since you only want to run it once, could you give the user a cookie that lasts until the browsing session is over when they fist click the button? If they have the cookie, then you could skip over the line of code that you only want to run once.

Your code doesn't work at all. The main issue is how you try to catch click event.
<asp:Button ID="Button1" runat="server" onclick="Button1_Click1" Text="Next" />
It means that Button1_Click1 function runs at server. No client-side event occurs. To do something on client side you have to add onclientclick="someFunction()" to your button declaration.
OK, you add this. Now go to javascript.
function someFunction(){
var clickOnce = getCookie('clickOnce');
//Look #Darkrifts comment (link) how to do it.
//Just in case I reproduce the link http://www.w3schools.com/js/js_cookies.asp
if(!clickOnce || confirm('blah blah')){
document.cookie = 'clickOnce=1';
//no need to return anything
}
//if a visitor doesn't click "ok" then the popup appear again
}
It is also possible to set Session["clickOnce"] = true; on server side and use it from Page_Load server side handler but it may not work if a visitor return to the page using browser Back button.
protected void Button1_Click1(object sender, EventArgs e){
Session["clickOnce"] = true;
//more code
}
protected void Page_Load(object sender, EventArgs e){
if(Session["clickOnce"] != true)
Button1.OnClientClick = "someFunction()";
else
Button1.OnClientClick = "";
//more code
}

This can be achieved in multiple ways. You need to select the most efficient approach for your need. First of all you need to understand the ASP.Net page life cycle, persisting information between pages and ViewState.
In a nutshell...
Whenever your page reloads all elements (including JavaScript variables, be it global or local variables) in your page get's initialised. And then a feature in ASP.Net comes into play. I.e. ViewState. If this is set to true in page level or for each control it'll persist information of the controls in the page (depends on how you set this). But, this is page specific.
And, you could persist information between pages using following approaches
Query string
Session variables
Cache
Form posts
Cookies
Data store (e.g. text, xml or any other database/ data store)
Before you use any of the above mentioned approaches you must think about your requirement. #Alex Kudryashev came up with a good example while I was writing this answer. Let me know if you need example with a different approach or any clarifications.

Related

Jquery form submit of ASP.Net form : request(txtname) <> txtname.text

I am trying to do something that should be simple. I have found shortcut.js
and am using it to fulfill a request. I need to do a page save when they press/type CTL-S. A normal odl school synchronous call is fine.
[Yes, CTL-S would normally save the HTML page to a file.]
First I will explain the issue, then I will walk through the particulars.
Here is the js snippet that binds the shortcut. Simply call the buttons click event...
shortcut.add("F11", function(){
$('#ctl00$cp1$btnSave').click();
}
);
Upon invoking the shortcut, the keystrokes are captured and the save button is fired. My code behind is called.
It seems the FORM values in the HTTP request are not getting mapped to the control variables. I may not quite be saying that right... consider this :
here ctl00$cp1$txtname is the uniqueId of the textBox control.
request('ctl00$cp1$txtname') = "newValue"
txtname.text = "oldvalue"
If I go back and click on the button w my mouse, same button, same form....
request('ctl00$cp1$txtname') = "newValue"
txtname.text = "newvalue"
This is the case in form.load. So whenever this mapping is happening/not happening, it is pretty early in the page life cycle.
This is not unique to a particular control. All the controls suffer the same issue.
here is the SAVE button at design time
<asp:Button ID="btnSave" runat="server"
Text="Save" class="submit" CssClass="buttonblue" UseSubmitBehavior="false" />
here is what it looks like when it is rendered
<input type="button" name="ctl00$cp1$btnSave" value="Save" onclick="javascript:__doPostBack('ctl00$cp1$btnSave','')" id="ctl00_cp1_btnSave" class="buttonblue">
I notice that at a DOM level of thinking, a mouse click should fire __doPostBack. No more, no less. So I change the shortcut code to do the same
shortcut.add("F11", function(){
__doPostBack('ctl00$cp1$btnSave', '');
}
);
This does not resolve the problem.
Again, this is client side stuff, nothing really tricky going on. A look at the page source shows __doPostBack is rendered this way
var theForm = document.forms['aspnetForm'];
if (!theForm) {
theForm = document.aspnetForm;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
While I am at it , I also try
shortcut.add("F11", function(){
$('#aspnetForm').submit();
}
);
this also does not resolve the problem.
I'm not trying to do anything clever, or even asynch, I just want the form to submit via JS.
My primary question is : why is asp.net not behaving as I would expect it to.
Specifically, why is it not mapping the request.form values to the control variables.
I would think that
a) clicking the button
b) calling (#btn).click()
c) calling __doPostback (with exactly the same parms that clicking would use)
would yield identical results.
I am failing to understand something here.
An interesting data point is that I get the same unwanted behavior by calling ('#form').submit()
telerik radTextBox controls somehow interfere with the asp.net process. By replacing them with regular text boxes, I was able to get the desired behavior.
this has been a thorn in my side for weeks.

add "please wait" javascript modal to aspx DetailView insert button

Using insert functionality of an aspx DetailsView. Would like to show a javascript modal popup window while the new record is processed and added to the database. I can hook the button click in DetailsView_ItemCommand. It's not working, so I started trying to figure out whats going on by simply displaying a javascript Alert() popup. But can't get that to even work. Here's the relevant DetailsView_ItemCommand:
protected void DetailsViewInsertFPL_ItemCommand(object sender, DetailsViewCommandEventArgs e)
{
if (e.CommandName == "Insert")
{
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "waitMessage", "alert('Please wait while your request is processed');", true);
return;
}
}
After the record is inserted, there is a redirect to another aspx page.
Can anyone steer me down the right path? I'll be looking at some of the aspx page and DetailsView properties next to see if something there isn't set correct.
You cant just use
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "waitMessage", "alert('Please wait while your request is processed');", true);
then preceeded by a
response.redirect("toanotherpage.aspx");
ScriptManager.RegisterStartupScript will render your script after all the elements in the page (right before the form's end tag) hence not executing it when you use response redirect on the same code block.
To achieve what you want you could do one of the following solutions,
Create a Javascript and place you the redirect or for this instance
window.location there after the Alert message you want
Create a pop-up modal using other methods like bootstrap, on the modal declare a button with a code for response.redirect.
Alex Kudryashev's suggestion to enclose the DetailView within an asp:UpdatePanel and use the asp:UpdateProgress to show the "please wait while your request is processed" gave me the solution I needed in this case.
Infrequent user here, so not sure how to give the points to Alex as his suggestion was a comment rather than an answer. Feel free to let me know how to handle the votes in that case.
Thanks!!!! I've been banging my head against the wall for a couple of days to get this one working.

Why is Post back not triggered when user navigates away from page, but triggered on close?

I have the following code to detect user navigation or close.
The post back is triggered on close but not when navigated away.
If i place a alert message it is triggered at all times.
Oh and there is a timer on the page which is actually disabled after first tick. but there is always a post back triggers when navigating away with eventtarget timer. I think this may be because i have cleared cache for the previous page.
<script src="Scripts/jquery-1.4.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(window).bind("beforeunload", function () {
alert("u r navigating away"); // this message gets triggered at all times.
__doPostBack('callPostBack');
});
</script>
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
string eventTarget = this.Request["__EVENTTARGET"];
string eventArgument = this.Request["__EVENTARGUMENT"];
if (eventTarget != String.Empty && eventTarget == "callPostBack")
{
//do task
}
}
}
Thanks in advance.
This is not logical, when the user go way from the page or close it, you can not actually make a post back, think about, the user close the page and you try to reload it with a post back? And if your action works then you have a dead loop, you make post back and keep open the page that user try to close. Anyway if the user close the page, or change it, this is first priority and the post back are not working.
If you try to make ajax call there you also fails because the ajax stops after the page close and this is going to be done (the page close) before the ajax trigger.
You need to re-desing your action.

Conditional confirm prompt in asp.net code behind

I have looked around for a way of implementing this. Here is a pseudocode representation of what I have:
bool hasData = ItemHasData(itemid);
Confirm = "false"; // hidden variable
if (hasData)
{
//Code to call confirm(message) returns "true" or "false"
if (Confirm == "true")
{
//Delete item
}
else if (Confirm == "false")
{
return;
}
}
The code to call confirm uses a asp:Literal control and sets it equal to the confirm. I can get the popup but only after the function exits. And it does nothing with the conditions after that.
The general consensus seems to be that calling the javascript at that specific line is impossible (makes sense due to the server side/client side gap), but how can I achieve this? I tried using the ConfirmButtonExtender from the ASP.NET AJAX Toolkit but I couldn't interact with the confirmbuttonextender object from the code behind when the object is set to runat="server".
edit:
Sorry, I did miss those tidbits. Thanks Icarus.
The control itself is the GridView (the pseudo version is actually from the gvData_RowCommand function)'s rowcommand. The first check looks to see if the CommandName is DeleteItem and if so goes into this.
The gvData's columns are set based off a list of headers (and the dataset) passed as the table it is working against is for multiple items with different required information. The gvData's data is there, I just need to get a Yes/No (or in reality it'll end up being Ok/Cancel) dialog to verify they want to delete the item when there is data.
One method I end up using in some situations is to have a Panel that displays the Confirm / Cancel buttons. This avoids the need to handle JavaScript events and uses ASP.NET entirely.
<asp:Panel ID="pDeleteConfirm" runat="server"
CssClass="AlertDialog"
Visible="False">
<p>Do you wish to delete the selected record?<br />
<asp:Button ID="btDeleteYes" runat="server" OnClick="btDelete_Click" Text="Delete" />
<asp:Button ID="btDeleteNo" runat="server" OnClick="btDelete_Click" Text="Cancel" />
</p>
</asp:Panel>
<asp:GridView ID="gvData" runat="server"
AutoGenerateColumns="False"
CssClass="GridView"
DataKeyNames="ID"
DataSourceID="sqlData"
EmptyDataText="There is no data entered in the system."
OnRowDeleting="gvData_RowDeleting">
......
</asp:GridView>
I use the OnRowDeleting event to show the Panel
protected void gvData_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
// Show confirmation dialog
pDeleteConfirm.Visible = true;
// Select the row to delete
gvData.SelectedIndex = e.RowIndex;
// Cancel the delete so the user can use the confirm box
e.Cancel = true;
}
Handle the button Click events
protected void btDelete_Click(object sender, EventArgs e)
{
Button bt = (Button)sender;
switch (bt.ID)
{
case "btDeleteYes": // they confirmed a delete
sqlData.Delete();
break;
case "btDeleteNo": // they clicked cancel
// Do nothing
break;
default:
throw new Exception("Unknow button click in btDelete_Click");
}
// clear selection and hide the confirm box
gvData.SelectedIndex = -1;
pDeleteConfirm.Visible = false;
}
This isn't JavaScript but you can add in some UpdatePanels to do AJAX work on it.
Just one method to do it through ASP.NET rather than JavaScript handling.
The job of your code-behind is to render HTML out to the browser. It does this, and then the socket is closed and your server side code is no longer executing.
You'll have to implement this logic using a Javascript function on the client side.
Are you attempting to warn the user if there's data loaded before they take a certain action? Or perhaps before they try to leave the page? You'll have to popup the alert using script when that action happens on the page.

How do I stop the Back and Refresh buttons from resubmitting my form?

I am doing web development.
I have a page to do with credit card, which when user click "refresh" or "Back", the transaction will be performed one more time, which is unwanted.
This include Browser top left "Back" & "Refresh" button, "right click->Refresh/Back", press "F5" key.
This is to be done on certain cgi page only, not all of them.
Can this be done using Javascript? Or any other method?
The standard way is to do it in 3 steps.
the form page submits fields to processing page
processing page processes data and redirects to result page
result page just displays results, reloading it won't do any harm.
This breaks the basic browser user experience model...users should always be able to use the Refresh and Back buttons in their browser. Recommend that you fix your page another way.
If you update your question to include the server language/platform/technology that you are using then someone might be able to suggest a solution.
The simple fact that resubmitting the form generates a duplicate transaction is worrying. You should have some sort of check to ensure each submit of form data is unique.
For example, the page which would submit the form should be given a unique ID that gets submitted with the form. The business logic should then be able to recognise that the form submitted has already been processed (as the (no longer) unique ID will be the same), so ignores the second attempt.
The 'standard way' still doesn't stop clients from clicking the back button twice... or even going back and resubmitting the form if they don't think (for whatever reason) it has been processed.
generate a random string and store it in session,
then output it to your form as a hidden value,
check the submitted and store variable, if matches process your request,
go to 1.
Place this code on the form page
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.Now-new TimeSpan(1,0,0));
Response.Cache.SetLastModified(DateTime.Now);
Response.Cache.SetAllowResponseInBrowserHistory(false);
You shouldn't try to "block" these actions.
What you should do is make sure that nothing happends when someone "double submits" the form.
and in some browser you canĀ“t even do that, and this is good!
The best way is to have enough session handling logic that you can recognise the 2nd (and onwards) attempt as "this is just a re-submission" and ignore it.
I didn't see this here so here it is.
Put a unique token in the form.
The submit button triggers an xmlhttp(ajax) request to the server to create a session variable named after the token with a stored value of 1.
The ajax request submits the form after receiving a positive state change.
The form processing script checks for the session variable withe the stored value of 1.
The script removes the session variable and processes the form.
If the session variable is not found, the form will not be processed. Since the variable is removed as soon as its found, the form can only be run by pressing the submit button. Refresh and back will not submit the form. This will work without the use of a redirect.
vartec:s solution solves the reload-problem, not the back-problem, so here are a solution to that:
The form page sets a session variable, for example session("fromformpage")=1
The processing page check the session variable, if its ="1" then process data and redirect to result page if any other than ="1" then just redirect to result page.
The result page sets the session variable to "".
Then if the user is pressing back button, the processing page will not do the process again, only redirect to process page.
I found the above Post/Redirect/Get explanations a little ambiguous
Here's what I followed and hopefully it helps someone in the future
http://wordsideasandthings.blogspot.ca/2013/04/post-redirect-get-pattern-in-php.html
Essentially the process based on the above solution is:
Submit from the FORM page to the processing page (or to itself)
Handle database or payment processing etc
If required, store user feedback message in a session variable, possible error messages etc
Perform header redirect to results page (or to original form page). If required, display custom message from processing page. Such as "Error Credit Card payment was rejected", and reset session variables.
Redirect with something like:
header("HTTP/1.1 303 See Other");
header("Location: http://$_SERVER[HTTP_HOST]/yourfilehere.php");
die();
The header redirect will initiate a GET request on "yourfilehere.php", because a redirect is simply that, a "request" to fetch data FROM the server, NOT a POST which submits data TO the server. Thus, the redirect/GET prevents any further DB/payments processing occurring after a refresh. The 301 error status will help with back button pressing.
Helpful Reading:
http://en.wikipedia.org/wiki/URL_redirection#HTTP_status_codes_3xx
http://www.theserverside.com/news/1365146/Redirect-After-Post
http://wordsideasandthings.blogspot.ca/2013/04/post-redirect-get-pattern-in-php.html
https://en.wikipedia.org/wiki/HTTP#Request_methods
http://en.wikipedia.org/wiki/Post/Redirect/Get
Just put this javascript on the html section of aspx page above head section
<script type = "text/javascript" >
function disableBackButton()
{
window.history.forward();
}
setTimeout("disableBackButton()", 0);
</script>
We need to put it on the html section of the page which we want to prevent user to visit by hitting the back button
Complete code of the page looks like this
<%# Page Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<script type = "text/javascript" >
function disableBackButton()
{
window.history.forward();
}
setTimeout("disableBackButton()", 0);
</script>
</head>
<body onload="disableBackButton()">
<form id="form1" runat="server">
<div>
This is First page <br />
<br />
Go to Second page
<br />
<br />
<asp:LinkButton ID="LinkButton1" runat="server"
PostBackUrl="~/Default2.aspx">Go to Second Page
</asp:LinkButton></div>
</form>
</body>
</html>
If you are using firefox then use instead of onload
If you want to disable back button using code behind of aspx page,than you need to write below mentioned code
C# code behind
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
string strDisAbleBackButton;
strDisAbleBackButton = "<script language="javascript">\n";
strDisAbleBackButton += "window.history.forward(1);\n";
strDisAbleBackButton += "\n</script>";
ClientScript.RegisterClientScriptBlock(this.Page.GetType(), "clientScript", strDisAbleBackButton);
}
We can also achieve this by disabling browser caching or cache by writing this line of code either in Page_load event or in Page_Init event
protected void Page_Init(object Sender, EventArgs e)
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1));
Response.Cache.SetNoStore();
}
Doing this,user will get the page has expired message when hitting back button of browser
Demo is :
This code works for not back from current page me..
Here I put a code which helps you , not open contextmenu and on browser reload ask you leave a page or not...
I am trying the ask click on browser back button
jQuery( document ).ready(function() {
document.onkeydown = fkey;
document.onkeypress = fkey
document.onkeyup = fkey;
var wasPressed = false;
function fkey(e){
e = e || window.event;
//alert(e.keyCode);
if( wasPressed ) return;
if (e.keyCode == 116 || e.keyCode == 8 || e.keyCode == 17) {
// alert("f5 pressed");
window.onbeforeunload = null;
return true;
}
}
window.onbeforeunload = function (event) {
var message = ''; // Type message here
if (typeof event == 'undefined') {
event = window.event;
}
if (event) {
event.returnValue = message;
}
return message;
};
jQuery(function () {
jQuery("a").click(function () {
window.onbeforeunload = null;
});
jQuery(".btn").click(function () {
window.onbeforeunload = null;
});
//Disable part of page
$(document).on("contextmenu",function(e){
return false;
});
});});
Thanks,

Categories

Resources