Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing values from one page to another in JavaScript [closed]

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?

like image 982
Ramkumar Avatar asked Jan 31 '14 07:01

Ramkumar


People also ask

How do I pass a value from one page to another in JavaScript?

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.

How do you pass input value from one HTML page to another?

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.

What is '$' in JavaScript?

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.


2 Answers

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"];
like image 106
Niels Avatar answered Sep 29 '22 08:09

Niels


Global variables in one page are not kept by the next.

If you want this client-side, you have three options (at least):

  1. Pass the variable to the next page on the query string, e.g.:

    window.location = "WebForm2.aspx?myvar=" + encodeURIComponent(myvar);
    
  2. Use a cookie (millions of examples online, I won't repeat them, bit of a pain to read the cookie).

  3. 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.

like image 28
T.J. Crowder Avatar answered Sep 29 '22 07:09

T.J. Crowder