Passing Variable through JavaScript from one html page to another page
Asked Answered
M

6

37

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?

Myxomatosis answered 4/1, 2015 at 12:49 Comment(4)
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.Troop
global variables are only global to the page. Maybe have a look at url parameters #980475 ?Wallacewallach
@Troop (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)Myxomatosis
Possible duplicate of Persist variables between page loadsStreet
P
72

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.

Provolone answered 4/1, 2015 at 13:16 Comment(7)
This is a good solution, but you haven't explained why you should use this. The OP does not understand global variables in JS.Snead
@Provolone Thanks. A realy great and easy solution. :) Do I have to consider (as LiamB said) some basic security with this solution?Myxomatosis
@Snead , 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)Provolone
in my page2 it says that localstorage is not definedHahnemann
And me it simply doesn't store it ... on page 2 the result of localStorage.getItem("key") is nullPrana
Is there a solution to pass data in memory from localhost/a.html to myhost/b.html?Shogun
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.Lael
M
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.

Mosul answered 4/1, 2015 at 12:51 Comment(0)
I
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.
Insobriety answered 4/1, 2015 at 13:16 Comment(2)
@Mosul 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.Insobriety
How to use session in simple html?Lindsaylindsey
L
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!

Latoyialatreece answered 16/3, 2020 at 23:4 Comment(0)
N
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.

Nickola answered 11/9, 2021 at 12:15 Comment(0)
C
1

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");
Counterclockwise answered 4/5, 2023 at 13:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.