i want to pass an asp session to javascript variable - javascript

Ok so this is my ASP code of Login page where on success I am creating one of the session which is Session["role"]="user" and i want to pass that value to HiddenField1 and then I am trying to get this value in JavaScript but when i console.log HiddenField value I am always getting null even though I've tried almost all suggested solutions...if anyone can solve the issue then please give a way
Asp code
if (dr.HasRows)
{
if(dr.Read())
{
//Response.Write("<script> alert( 'the user : "+dr.GetValue(8).ToString()+" Successfully Logged in')</script>");
Session["username"]=dr.GetValue(8).ToString();
Session["fullname"] = dr.GetValue(0).ToString();
Session["role"] = "user";
HiddenField1.Value = Session["role"].ToString();
Response.Write("<script> alert("+HiddenField1.Value+")</script>");
Session["status"] = dr.GetValue(10).ToString();
}
ScriptManager.RegisterStartupScript(this, GetType(), "popup", "MyAlertFunOnSucc()", true);
Response.Redirect("homePage.aspx");
}
JAVASCRIPT in the masterpage Head
<script type="text/javascript">
var array_store;
array_store = document.getElementById("HiddenField1").value;
console.log(array_store);
</script>
And this is my hiddenField
<asp:HiddenField ID="HiddenField1" runat="server" />
and this the ERROR
homePage.aspx:28 Uncaught TypeError: Cannot read properties of null (reading 'value')

Ok, so you might have spend some time making it CRYSTAL clear that you have a master page here?
however, you have this code:
HiddenField1.Value = Session["role"].ToString();
Response.Write("<script> alert("+HiddenField1.Value+")</script>");
Session["status"] = dr.GetValue(10).ToString();
}
ScriptManager.RegisterStartupScript(this, GetType(), "popup", "MyAlertFunOnSucc()", true);
Response.Redirect("homePage.aspx");
You do realize what a response redirect does, right? It blows out the current page, the current class, and the current controls. You then say please forget about this page, and now re-direct to a WHOLE NEW page. (home page).
So, how can you inject a script, but THEN decide to dump the whole current page not send it to the client, and THEN re-direct to a whole different page????
What this means is that you need to put/place/have that code that sets the hidden control, and the register script MOVED to the home page code. So, on home page (is PostBack = false), you can set the hidden field, and THEN do your register script.
but, with your current setup, by executing a redirect to a whole new page, your register script, and in fact even your setting of the hidden field - both make no sense at all if after setting the hidden field, and tossing in a scripts to run?
YOU THEN SAY FORGET about all that and now transfer TRANSFER to a whole new and different page.
So, move your code that sets the hidden field, and register script to the load of the home page (page load event).

You can use a handler (.ashx file) for returning session value and then a ajax call in the front side to get that value , or a method with [WebMethod] attribute in backend side and a ajax call at front side to get session value.

Related

Browser back-button displays the preserved page state sent by server but any DOM modifications done using javascript is not getting preserved

The code snippet (in C#) that is used to trigger the JavaScript code from code-behind is as:
int returnValue = SaveStudent("John", "XII"); // SaveStudent() is a C# function that saves the student details in DB and returns studentId.
hdnStudentId = returnValue ; // hdnStudentId is a hidden-field control
ScriptManager.RegisterStartupScript(this, this.GetType(),
"ShowStudent", "showStudentDetails();",true);
The definition of "showStudentDetails()" JavaScript method is as:
function showStudentDetails(){
If($('[id*=hdnStudentId]').val() > 0){
// show the popup
}
}
Here is the description of the issue:
In a web-page 'WebPage1.APSX', after saving the data in DB, I display
a bootstrap popup using ScriptManager Class (as mentioned above).
Here I set the value of a hidden-field variable to the inserted rowid
that is inserted in DB(say 12345) .
The ScriptManager class
successfully registers the script in DOM and displays the popup.
Thereafter I reset the Here hidden-field variable to -1. In the
popup, I have a button control that redirects to another page
'WebPage1.APSX'.
$('[id*=hdnStudentId]').val('-1');
Now user clicks on 'browser back-button', it doesn't hit the server-side code and
renders the UI based on previous instance of page sent by server.
As this is previous instance of page sent by server, hidden-field
variable gets set to '12345' instead of -1 (not sure why, we already
did reset the value to -1) and display the popup again.
Requirement: When user clicks on 'browser back-button', we need to remember the previously manipulated data in DOM as well(i.e. $('[id*=hdnStudentId]').val('-1');) so that we can avoid to display the popup on browser back-button click.
You need to checkout Browser history API to save your page state in the history when no server involved, here is mdn doc https://developer.mozilla.org/en-US/docs/Web/API/History_API
The DOM window object provides access to the browser's history through
the history object. It exposes useful methods and properties that let
you move back and forth through the user's history, as well as --
starting with HTML5 -- manipulate the contents of the history stack
and also an example of Ajax navigation https://developer.mozilla.org/en-US/docs/Web/API/History_API/Example. hope that helps!
Thanks #Salus .. I followed your advise.. And finally the following code-snippet worked for me..
I used 'history.pushState();' method just after showing the popup:
$('#divStudentDetails').modal('show');
history.pushState(null, null, "");

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.

Javascript client & asp.net event handler timing issues - how to solve?

Simple web site with master page and multiple child pages.
In page_load, master page looks for session variable containing a value and if it's there, uses
Page.ClientScript.RegisterStartupScript(this.GetType(), "SessionAlert", "SessionExpireAlert(" + sessionTimeout + ");", true);
This kicks off a timeout alert, which works fine.
There is a server-side button on one child page that effectively ends the user interaction on the page and leaves a message stating "go and log in again if you want to do more stuff". When this button is clicked, I want to clear out the session variable (easy) and end the running timeout warning alert script (not so easy).
As the Master "page_load" event fires BEFORE the button handler, at the time the page reloads, it restarts the timeout script. When it hits the button event handler and clears the session variable, it's too late as the script is already running.
I've tried using "registerclientscriptblock" to inject immediate javascript to call the "clearTimeout()" client side function I have, but it doesn't seem to be able to find the function which exists on the master page and errors.
This seems to be a classic "chicken and egg" scenario and I can't see the wood for the trees. Could someone please point me in the right direction here before I drive myself mad!?
edited to add bit of javascript code:
Currently the master page function "SessionExpireAlert" referenced by the page_load code contains among other things this:
window.updateInterval = setInterval(function () {
seconds--;
document.getElementById("idleTime").innerHTML = convertTime(seconds);
document.getElementById("expireTime").innerHTML = convertTime(seconds);
}, 1000);
RegisterStartupScript will add the script to the end of the body, so the DOM is ready when it runs. As long as you always use RegisterStartupScript after that then the scripts will be added and executed in the order you create them.
Basically, RegisterClientScriptBlock is most likely going to place the script before any scripts added with RegisterStartupScript.
Have you considered putting this in Page_PreRender instead:
Page.ClientScript.RegisterStartupScript(this.GetType(), "SessionAlert", "SessionExpireAlert(" + sessionTimeout + ");", true);
With an appropriate check first to see if it is necessary?

Call JavaScript function after Telerik RadPageView finishes loading?

I'm using Telerik UI for asp.net. Specifically I'm using RadTabStrip with partial page postbacks to allow the user to tab through different sets of data. When the user clicks a tab, some code executes and loads data just for that tab.
I've figured out how to execute codebehind: I set the OnTabClick property of the RadTabStrip, and then in codebehind I check what tab was clicked.
E.g.
protected void tab_Click(object sender, RadTabStripEventArgs e)
{
if (e.Tab.Text == "Info")
{
populateInfoTab();
}
}
private void populateInfotab()
{
// Do some stuff
}
However, I can't figure out how to execute client side javascript after a specific tab is clicked. What I tried:
Set OnClientTabSelected property, and then add some javascript:
function tab_ClientClick(sender, args)
{
var tab = args.get_tab();
if(tab.get_text() == "Info")
{
alert("Tab Clicked");
}
}
The problem is that I need to set the InnerHtml of some div in the clicked pageview after it is clicked. The div does not exist on page load (that specific RadPageView is hidden) so I cannot set it then. Once the user clicks into the tab, and after the page view loads, I need to be able to update the div's InnerHtml through JavaScript.
How would I go about doing this?
First option - if you do not set the RenderSelectedPageOnly property to true, all page views will be rendered on the initial load and you will be able to use JS to find/modify elements in them.
Second option - just set the content from the server as soon as you load the UC, this will usually make things simpler.
Third option - use client-side events (offered by the native PageRequestManager class or the RadAjaxManager, depending on how you setup your AJAX interactions) to execute when the response is received. The difficulty here is to determine which is the postback you need. Looking for the desired element and only executing logic if it exists is the simplest flag you can opt for.
Fourth option - register a script from the server code that will call your function, something like:
populateInfoTab();
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "someKey", "myDesiredFunction()", true);
where you may want to use the Sys.Application.Load to ensure it is executed later than IScriptControl initialization.

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