Skip to content Skip to sidebar Skip to footer

Javascript Passing Variables To The Next Page (without Php)

I am a beginner in html and javascript so your help will be much appreciated. I am creating a page that accepts values x and y from a form and enters it into a graph. The graph is

Solution 1:

Use window.localStorage

Put the following literal object in some js file that you will refer to from the current and the next page (or just paste the object wherever necessary).

var xyStore =
    {
        GetX: function () {
            return JSON.parse(localStorage.getItem("x"));                
        },
        GetY: function () {
            return JSON.parse(localStorage.getItem("y"));                
        },
        SetX: function (x) {
            localStorage.setItem("x", JSON.stringify(x));
        },
        SetY: function (y) {
            localStorage.setItem("y", JSON.stringify(y));
        },
   };

use in current page:

xyStore.SetX(12);

use in next page:

alert(xyStore.GetX()); // alerts: 12

EDIT

Following @RokoC.Buljan comment, this functionality can be expanded as follows:

            Get: function (name) {
                return JSON.parse(localStorage.getItem(name));                
            },
            Set: function (name, val) {
                localStorage.setItem(name, JSON.stringify(val));
            }

Solution 2:

Use a simple form on the first page that is configured with method="GET" and action="/page2.html". The input fields within the form should also have a name attribute filled in, for example <input name="x">. Then when you press the submit button in your form, it will pass along the field names and values as a querystring to the second page. For example /graph.html?x=123&y=456.

On this second page you want to read these values, so you need to parse the querystring which is located in window.location.search. There are various ways of doing this, but no built-in feature (it will always be a string, for example x=123&y=456 that you need to parse). I will leave that open as you mention it is a school project and that last bit would be the next challenge ;)

(localStorage as described by @remdevtec is also an option of course.)


Post a Comment for "Javascript Passing Variables To The Next Page (without Php)"