Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Variable through JavaScript from one html page to another page

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?

like image 781
Kronwied Avatar asked Jan 04 '15 12:01

Kronwied


People also ask

How do you send a variable from one HTML page to another?

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.


2 Answers

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.

like image 173
potasmic Avatar answered Sep 19 '22 15:09

potasmic


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.

like image 39
LiamB Avatar answered Sep 21 '22 15:09

LiamB