Michael Capawana
Michael Capawana

Reputation: 9

Java Script: Passing variables between html pages

I am practicing making an e-commerce site. I am struggling passing my javascript variable between the shopping cart page to the checkout page. I tried following this example:

page one:
<a href="example2.html?myVar1=42&myVar2=66" >LINK</a>

page 2:

var qs = new Querystring();

var v1 = qs.get("myVar1");

var v2 = qs.get("myVar2");

I could not get it to work because my webpage threw an error about not recognizing QueryString, so I am currently trying like this by using window.localStorage as follows:

Page 01:

<button class="checkout" type="button" onClick="window.location.href='checkout.html'; window.localStorage.setItem("total",total)">Checkout</button>


Page 2:

var name = window.localStorage.getItem("total");
Currently, I am throwing a console.log(total) on the 2nd page but it returns "null" each time. Any idea why it's not catching the value from the first page? Please help. If you have suggestions or a solution for either method, it would be much appreciated. I feel like I'm really close with the 2nd method, I may just be missing something on the page 1 portion, thanks in advance.

Upvotes: 1

Views: 288

Answers (1)

JakeParis
JakeParis

Reputation: 11210

To fix your first method (passing variables between pages via a query string), you'd probably want something like:

// page one:
<a href="example2.html?myVar1=42&myVar2=66" >LINK</a>

// page 2:

var query = window.location.search;
if( typeof query !== 'undefined' ) {
    var params = {},
        parts
    ;
    // take off the ? and split into groups of key=value strings
    query = query.replace('?','').split('&');

    // split key=value strings into a usable object
    for(var i=0;i<query.length;i++){
        parts = query[i].split('=');
        params[ parts[0] ] = parts[1];
    }

    // now access your variables like so:

    params.myVar1 // is now "42" (a string)
    params.myVar2 // "66"

}

Upvotes: 1

Related Questions