36

I have two pages - "page 1" and "page 2". On page 1 there's an text-box with a value of e.g. 100 and a button at the end.

By pressing the button I want javascript to save the value of the textbox in a global (?) variable and jump to page 2. With "window.onload" I want a second Javascript-function to alert the value saved at page1.

Here's my Javascript code:

<script type="text/javascript">

var price; //declare outside the function = global variable ?

function save_price(){

    alert("started_1"); //just for information

    price = document.getElementById('the_id_of_the_textbox').value; 

    alert(price); //just for information         
}

<script type="text/javascript">

function read_price(){

    alert("started_2");

    alert(price);

}

On "page 1" I have this send-Button with:

<input class="button_send" id="button_send" type="submit" value="Submit_price" onclick="save_price();"/>

It starts the Javascript function and redirects me correctly to my page2.

But with this ont the second page:

window.onload=read_price(); 

I always get an "undefined" value of the global variable price.

I've read a lot about those global variables. E.g. at this page: Problem with global variable.. But I can't get it working...

Why is this not working?

Nisarg Shah
  • 14,151
  • 6
  • 34
  • 55
Kronwied
  • 381
  • 1
  • 3
  • 4
  • 2
    You misunderstood what “global variables” are in JavaScript in the browser. They are still tied to the page they were set in, they do not exist in other pages. – CBroe Jan 04 '15 at 12:53
  • global variables are only global to the page. Maybe have a look at url parameters http://stackoverflow.com/questions/979975/how-to-get-the-value-from-url-parameter ? – nha Jan 04 '15 at 12:58
  • @CBroe (and nha) Thank you! Didn't knew that they were still tied to the page. I thaught they are "realy" global (valid for all webpages) – Kronwied Jan 04 '15 at 14:40
  • 1
    Possible duplicate of [Persist variables between page loads](https://stackoverflow.com/questions/29986657/persist-variables-between-page-loads) – Liam Dec 18 '17 at 15:31

6 Answers6

71

Without reading your code but just your scenario, I would solve by using localStorage. Here's an example, I'll use prompt() for short.

On page1:

window.onload = function() {
   var getInput = prompt("Hey type something here: ");
   localStorage.setItem("storageName",getInput);
}

On page2:

window.onload = alert(localStorage.getItem("storageName"));

You can also use cookies but localStorage allows much more spaces, and they aren't sent back to servers when you request pages.

potasmic
  • 1,057
  • 8
  • 11
  • 2
    This is a good solution, but you haven't explained why you should use this. The OP does not understand global variables in JS. – ColBeseder Jan 04 '15 at 13:28
  • @potasmic Thanks. A realy great and easy solution. :) Do I have to consider (as LiamB said) some basic security with this solution? – Kronwied Jan 04 '15 at 14:42
  • @ColBeseder , Krownied: localStorage is per-domain. Other sites can not access your localStorage unless you've included other scripts from other sources (for example, Google Analytics). sessionStorage expires when you close the tab. Cookies have shorter expiration time than localStorage. However, if data contains sensitive info, you should invest in a back-end exchanging scheme instead of storing right into the browser, which users can view, edit, etc. (just like cookies) – potasmic Jan 05 '15 at 14:29
  • in my page2 it says that localstorage is not defined – Alberto Martínez Apr 25 '17 at 09:29
  • And me it simply doesn't store it ... on page 2 the result of `localStorage.getItem("key")` is `null` – Revolucion for Monica Oct 21 '17 at 15:10
  • Is there a solution to pass data in memory from localhost/a.html to myhost/b.html? – Rico Suter Dec 18 '18 at 23:52
  • This is a good solution +1, however, I suppose users cannot bookmark this page (like always redirects me to id = 5) if you use local storage instead of query string. – Near Jul 13 '19 at 02:46
9

Your best option here, is to use the Query String to 'send' the value.

how to get query string value using javascript

  • So page 1 redirects to page2.html?someValue=ABC
  • Page 2 can then read the query string and specifically the key 'someValue'

If this is anything more than a learning exercise you may want to consider the security implications of this though.

Global variables wont help you here as once the page is re-loaded they are destroyed.

Community
  • 1
  • 1
LiamB
  • 18,243
  • 19
  • 75
  • 116
4

You have a few different options:

  • you can use a SPA router like SammyJS, or Angularjs and ui-router, so your pages are stateful.
  • use sessionStorage to store your state.
  • store the values on the URL hash.
Martin
  • 15,820
  • 4
  • 47
  • 56
  • @LiamB makes a very good point. My suggestions, as well as his, have a security implication where values can be changed by the user outside of the application: either by changing the querystring parameters, hash parameters, localStorage data or by other means. You should always do validation on your backend service of the data. – Martin Jan 04 '15 at 13:38
  • How to use session in simple html? – Amir Nov 05 '18 at 07:21
3

To do this, I recommend sending data within the link data. This is a very simple way of doing it without PHP. Simply get the link in the second page and replace the previous link with "".

Page_One.html:

<script>
    //Data to be transfered
    var data = "HelloWorld";

    //Redirect the user
    location.replace("http://example.com/Page_Two.html?" + data);
</script>

Page_Two.html :

<script>
//Get the current link
var link = window.location.href;

//Replace all content before ? with ""
link = link.replace("http://example.com/Page_Two.html?","");

//Display content
document.write("Page_One.html contains:" + link + "");
</script>

Hope it helps!

1

I have a simple Approach rather (Pure JS): Page One :

<a href= "www.example.com/mypageTWO.html?gtk=SGVsbG8gV29ybGQh==">Goto Your Info</a>

Note : You've to encode your GTK value (i.e parameter value) in Base64

Next is Page TWO :

    <script>

    // first we get current URL (web page address in browser)
    var dloc= window.location.href;

    //then we split into chunks array
    var dsplt= dloc.split("?");

//then we again split into final chunk array, but only second element
//of the first array i.e dsplt[1] 

    var sanitize= dsplt[1].split("=");

    // now here comes the tricky part, join all elements into single //string. IT may be the case, that base64 string contain '=' sign, we shall find it

    var dlen= sanitize.length;
    var FinString= "";
    // we will start from 1, bcoz first element is GTK the key we don't // want it
    for(i=1;i<dlen;i++)
    {    
    FinString= FinString+sanitize[i];
    }
    // afterwards, all the Base64 value will be ONE value.
    // now we will convert this to Normal Text
    var cleantxt= window.atob(FinString);
    document.getElementById("yourname").innerHTML= "Your Name is : <b>"+cleantxt+" .";

You can do anything with the parameter decoded info... Like Redirecting visitor immediately to another page thru a "POST" method form automatically submitted by Javasript to Lead a php page finally, without an visible parameters, but with invisible hidden parms.

Shivam
  • 11
  • 1
0

There is Window: sessionStorage property. https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage

It also cleans data when page is closed,compatible with all browsers

// Save data to sessionStorage
sessionStorage.setItem("key", "value");

// Get saved data from sessionStorage
let data = sessionStorage.getItem("key");
Papahh
  • 11
  • 8