Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass an array to a new page using javascript?

hi everyone i need to pass an array value to a new html page. i tried but the array value is always resetting

here is my code

var cart=[];
var jumlah=0;
var total=0;


function add(index)
{
if(index==1)
{
    jumlah=prompt("masukan jumlah");
    if(jumlah==0||jumlah<0||jumlah==null)
    {
        alert("harap masukkan jumlah, dengan format yang benar");
    }
    else
    {
    total=jumlah*500000;
    cart.push('Razer Destructor Battlefield @ IDR 500.000|| Jumlah '+jumlah+' || total '+total);
    for(var i=0;i<cart.length;i++)
    {
        alert("barang telah di tambahkan ke keranjang");
    }
    }
}
else if(index==2)
{
    jumlah=prompt("masukan jumlah");
    if(jumlah==0||jumlah<0||jumlah==null)
    {
        alert("harap masukkan jumlah dengan format yang benar");
    }
    else{
    total=jumlah*2020000;
    cart.push('Razer blackwidow ultimate mechanical keyboard for gaming @ IDR 2,020,000|| Jumlah '+jumlah+' || total '+total);
    alert("barang telah di tambahkan ke keranjang");
    }
}}

i need to pass that cart[] array from product.html to a a new page called cart.html

can u guys help me? sorry im a beginner and sorry for bad english. thanks for ur help!!

like image 583
user2978983 Avatar asked Dec 25 '22 15:12

user2978983


2 Answers

You should have a look to localStorage

window.localStorage.setItem("cart", JSON.stringify(cart)); // Saving
var cart = JSON.parse(window.localStorage.getItem("cart")); // Retrieving
like image 127
Neovov Avatar answered Dec 28 '22 07:12

Neovov


If you're supporting recent browsers, to save do:

localStorage.setItem('cart', JSON.stringify(cart));

To retrieve it from other html page in the same domain:

var cart = JSON.parse(localStorage.getItem('cart'));

If you have to support old browsers, apply the same logic but saving in cookies.

Cheers

like image 31
Edgar Villegas Alvarado Avatar answered Dec 28 '22 06:12

Edgar Villegas Alvarado