Passing a variable using JavaScript from one html page to another page

I have two pages - "page 1" and "page 2". On page 1 there is a text box with a value, for example. 100 and a button at the end.

By clicking the button, I want javascript to save the text field value in a global (?) Variable and go to page 2. Using "window.onload" I want the second Javascript function to display the value stored on page1.

Here is 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 submit button with:

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

It runs the Javascript function and redirects me correctly to my page.

But at the same time on the second page:

 window.onload=read_price(); 

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

I read a lot about these global variables. For example. on this page: Problem with a global variable .. But I can't get it to work ...

Why is this not working?

+7
javascript variables html undefined global
source share
3 answers

Without reading your code, but only for your script, I would decide using localStorage . Here is an example, I will use prompt() for brevity.

On page 1:

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

On page 2:

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

You can also use cookies, but localStorage allows a lot more spaces, and they are not sent back to the servers when requesting pages.

+17
source share

Your best option here is to use a query string to "send" the value.

how to get query string value using javascript

  • So, page 1 is being redirected to page2.html? someValue = ABC
  • Page 2 can then read the query string and, in particular, the key "someValue"

If this is something more than a training exercise, you might want to consider the safety implications of this.

Global variables will not help you here, as soon as the page is reloaded, they will be destroyed.

+4
source share

You have several different options:

  • you can use a SPA router like SammyJS, or Angularjs and ui-router, so your pages are discreet.
  • use sessionStorage to store your state.
  • save the values ​​in the hash of the URL.
0
source share

All Articles