Alert message on button click event - javascript

I have a button and textbox on my page aspx and on button click event I am displaying alert message.
Now when I run website and click on button it display message but after that when I press F5 (Refresh) it again display message. So my question how to remove message when I click F5.
Below is my code for button click:
protected void btnExport_Click(object sender, EventArgs e)
{
DisplayMessage("There is no data to Export.", this);
}
and
public void DisplayMessage(String strMessage, Control name)
{
string script = "<script language='javascript'>alert('" + strMessage + "');</script>";
ScriptManager.RegisterStartupScript(name, name.GetType(), "JSCR", script, false);
}

Change your script as follows
string script = "alert('hello');window.location.href='Default.aspx'";
where i assumed Default.aspx is your page

You are instigating a client side event from server side which usually does not make sense.
The behaviour you are noticing is correct, when you clicked that button a request is posted to the server which calls your button click handler which then registers the client side script when the response is returned. When you press F5 to refresh your browsers is posting that exact same request again to the server, so the button handler is fired again.
I advise you read a little about how Post And Gets
work as well as how postbacks work in ASP.

Related

LinkButton click doesn't trigger with no javascript

Web forms user control generating a LinkButton in PageInit:
LinkButton b1 = new LinkButton();
b1.Click += new EventHandler(Button_Click);
public void Button_Click(object sender, EventArgs e) {
//redirects to another page .. (no js defined here or in the ascx surrounding this button)
}
Why doesn't this wok when my javascript is disabled, if I used no js at all when creating the button?
How do I prevent this?
Yes this is webforms (sorry, unable to comment below).
The issue is that's how web forms manages its events with the server - as I understand it anyway (correct me if I'm wrong). Use html 5 instead. You can make the page postback to the server at the same url with a query string and then on the server grab the query string. Not the best solution but it works; it will look something similar to this:
In your page:
<form id="aForm">
<button id="abutton" type"submit" formaction="thisPage.aspx?redirect=true">click me</button>
</form>
In your page load event on the server:
if (IsPostBack) {
object something = Request.QueryString["redirect"];
if (something == null)
//not redirecting
}

Get values from modal popup in parent window's button click event

I need to display a modal popup from a aspx.cs page. I need to invoke the popup from server side because before the popup opens, I need to pass an ID into the popup via query string.
this is my code to display the popup.
protected void btnNote_Click(object sender, EventArgs e)
{
string queryStringParam = "some text"; // some server code here to get the string ready;
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "openNotePopup('"+ queryStringParam +"');", true);
}
And this is the javascript to get the parameter and launch the modal popup.
function openNotePopup(var param)
{
var noteResult = window.showModalDialog("AddEditNote.aspx?Note=" + param, "Add/Edit Notes", 'center:yes; dialogWidth:600px; dialogHeight:500px;');
document.getElementById("hidden_NoteText").value = noteResult;
}
When the popup is closed, I pass a string value as window.returnValue which is captured in the noteResult variable in client side.
Now I need to capture the popup close event in my server side. I can capture the event in client side but I need the event in server side so that I can pick up the value from the hidden field and process it.
How can I achieve this?
I found a thread that seems to tackle this very issue. Hopefully this is something similar to what you were looking for:
Javascript confirm message problem
I suggest you to write you own function on ShowDialog like this:
showNotePopup('NotePopup', title, closeNotePopup);
NotePopup - id of your popup;
showNotePopup should describe what you wanna see in your popup, how it will close;
closeNotePopup function you bind to popup closing and inside it you can make for example post-request and this way you'll catch on server when your popup is closing.

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.

Alert Message is not showing

I am new in development, I want to show the alert message on button click after that I want to redirect the on another page. my button code is like below:
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
Response.Write("<script type='text/javascript'> alert('Please wait for approval!');</script>");
Response.Redirect("~/profile/scrapbook.aspx?uid=" + Request.QueryString["uid"], false);
}
in this case alert is not working, If I remove the Response.Redirect then it will works properly.
Please suggest me how to call he alert message after that redirect on another page.
You are mixing server side and client side code.
The Response.Redirect("~/profile/scrapbook.aspx?uid= is server side and the Alert won't wait the action of the user to execute it...
What you will need is to do you redirect in Javascript or to use something else than an Alert for the message.
Solution 1
You display a Alert message in Javascript (client side) when the user press okay you do a redirect in Javascript.
Solution 2
You display a message in the HTML with a button in ASP with an event that will do a call to the server and redirect your user to the page you desire.
Add your script like this:
const string scriptString = "<script type='text/javascript'> alert('Your friend request sent to the user! Please wait for approval!');</script>";
ClientScriptManager script = Page.ClientScript;
script.RegisterClientScriptBlock(GetType(), "randomName", scriptString);
Do not use Response.Write to render your JavaScript. Use RegisterClientScriptBlock or RegisterStartupScript instead.
Your example should be using RegisterStartupScript, since it's rendering executing script, and not function declarations.

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