I want to know how I can pass a variable from one page to another using JavaScript
Here’s my code:
var currentBasketPrice = 0;
var quotes = new Array(
"A good painting to me has always been like a friend. It keeps me company, comforts and inspires.",
"A man paints with his brains and not with his hands.",
"A picture is a poem without words.",
"A work of art is the unique result of a unique temperament.",
"An artist cannot fail; it is a success to be one.");
var quotePerson = new Array(
"Hedy Lamarr",
"Michaelangelo",
"Horace",
"Oscar Wilde",
"Charles Horton Cooley");
var imgSrc = new Array ("images/hangings/1.jpg","images/hangings/2.jpg");
var prices = new Array (100,50);
var sizes = new Array ("450*350","100*50");
var inBasketPrices = [];
var inBasketNames = [];
function load(displayQuotes, displayBasket, displayProductInfo)
{
if (displayQuotes==true)//quotes
{
var quotenum = Math.floor(Math.random()*5 );
document.getElementById('quote').innerHTML= quotes[quotenum];
document.getElementById('quoteperson').innerHTML=" - " + quotePerson[quotenum];
}
if(displayBasket==true)
{
var list = $('#basketsidebar ul');
list.append('<button type="button">Checkout</button>');
}
if(displayProductInfo==true)
{
for (var i = 0; i < prices.length; i++)
{
var list = $('#products ul');
list.append('<li><img src="'+imgSrc[i]+'" width="525px" height="350px"/></li>');
list.append('<li>Price: £' + prices[i] +'</li>');
list.append('<li>Size: ' + sizes[i] +'</li>');
list.append('<button type="button" onclick="addToBasket(' + i + ')">Add To Basket</button>');
}
}
}
function addToBasket(itemAdded)
{
inBasketPrices.push(prices[itemAdded]);
var list = $('#basketsidebar ul');
list.append('<li>Price: £' + inBasketPrices[itemAdded] +'</li>');
}
I want to make it so that when the checkout button is clicked the user is directed to a new page, and the items currently in the basket are carried over. At the moment only the prices of the items get added to the basket.
I have no idea how to do this so if anyone could help it would be greatly appreciated.
Javascript is a language that gets executed by your browser on a defined page.
The relation between pages is handled by the HTTP protocol, and thus propagating data from one page another should be done with this protocol.
HTTP allows you to share data in three ways:
Data in the GET format is easy to write in Javascript, you only have to append
?var1=value&var2=value2to your URL. You can retrieve data by either using a server-side programming language or by analyzing the URL (see here). POST can be a little more tricky for your application, but can still be done. Cookies can also be an option, but are a bit different. Instead of following the HTTP request as GET/POST, Cookies are being held on the client computer. You can manipulate cookies via Javascript as shown in this tutorial.