Javascript – Passing Variable through JavaScript from one html page to another page

globalhtmljavascriptundefinedvariables

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?

Best Answer

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.