0

[Javascript Error]

Hello, I have a webpage which sets a cookie:

function start() {
var expirydate=new Date(); 
expirydate.setTime(expirydate.getTime()+(100*60*60*24*100));
setCookie('product',null,expirydate); 
window.location="mainpage.html";}
function setCookie(name,value,expires){
document.cookie = name + "=" + value + ((expires==null) ? "" : ";expires=" + expires.toGMTString())}

then another webpage accesses it:

function cart(productName) {
var expirydate=new Date();
expirydate.setTime(expirydate.getTime()+(100*60*60*24*100))
var productnames=getCookie('product')
alert(productnames);
var products=productnames+" "+productName;
setCookie('product',products,expirydate);
alert(products);
window.location = "cart.html";}

and adds (concatenates) the old value of the cookie with a new input by the viewer, and saves it.

This is for the purpose of a cart. Each time the viewer clicks "Add to cart" on the products page, the product name (productName) gets added to the cookie containing all the products the viewer has already added.

However, this doesn't seem to work. The webpage accessing the cookie resets it to null everytime it adds something to the cookie. Therefore, instead of a list of product names, I only get the name of the product the viewer last chose.

Please HELP! It's very very urgent! Thanks in advance.

user2257736
  • 81
  • 1
  • 1
  • Does this answer your question? [Cannot set cookies in Javascript](https://stackoverflow.com/questions/8105135/cannot-set-cookies-in-javascript) – Beginner Jul 05 '20 at 09:26

1 Answers1

0

I haven't worked too much with cookies, but maybe the cookie only stores one value at a time, which is why you only get the product that was last chosen. If there's any way to store an array inside a cookie, I would use an array, because it can store more than one item. If not, you could try storing multiple cookies. I don't know the code for this -- as I said, I haven't worked much with cookies yet.

Hope this helps!

Alex
  • 1
  • Oh I got it. Chrome denies file cookies. See this for more info http://stackoverflow.com/questions/8105135/cannot-set-cookies-in-javascript/15998274. I have answered the question right at the end. – user2257736 Apr 14 '13 at 11:00