In below code, the value is not passed from one page to another.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<script type="text/javascript">
function generateRow() {
var myvar = "testuser";
'<%Session["temp"] = "' + myvar +'"; %>';
window.location = "WebForm2.aspx";
}
</script>
<head>
<title></title>
</head>
<body>
<div runat="server">
<input id="Button1" type="button" onclick="generateRow()" value="button" />
</div>
</body>
</html>
What is the problem in above code?
There are two ways to pass variables between web pages. The first method is to use sessionStorage, or localStorage. The second method is to use a query string with the URL.
For sending data to two servelets make one button as a submit and the other as button. On first button send action in your form tag as normal, but on the other button call a JavaScript function here you have to submit a form with same field but to different servelets then write another form tag after first close.
The dollar sign ($) and the underscore (_) characters are JavaScript identifiers, which just means that they identify an object in the same way a name would. The objects they identify include things such as variables, functions, properties, events, and objects.
You cannot set a session with Javascript. Your output JS file will be exactly what you wrote down.
You can do it like this:
window.location = "WebForm2.aspx?temp=" + myvar;
And in Webform2 you can do:
Request.querystring["temp"];
Global variables in one page are not kept by the next.
If you want this client-side, you have three options (at least):
Pass the variable to the next page on the query string, e.g.:
window.location = "WebForm2.aspx?myvar=" + encodeURIComponent(myvar);
Use a cookie (millions of examples online, I won't repeat them, bit of a pain to read the cookie).
Use client-side session storage or local storage, both of which are covered here. Here's the client-side session storage example:
// Setting
sessionStorage.myvar = myvar;
// Getting (on the next page)
var myvar = sessionStorage.myvar;
(sessionStorage
is a global variable provided by the browser.)
This works on just about any browser you need to care about (IE8+, and modern versions of basically everything else).
Server-side, both option 1 and 2 would work, but 1 would make the most sense.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With