0

I am trying to save an array and restore it on another page using Cookies.

This is my code on Page 1:

var films = [];
SetCookie("cart", films);

Values are put into films through button on a cart, it stores values e.g. "Star Wars","Resident Evil".

On alert it is stored: Star Wars, Resident Evil

This is my code on Page 2:

function getMovie2() {
  var movie = [];
  movie = (GetCookie("cart"));

  var r = movie.length;
  alert(r);

  $("#table1").empty();

  for (var i = 0; i < r; i += 1) {
    $("#table1").append("<tr><td>" + movie[i] + "</td><td>");
  }
}

The lenght that I get from this is for EACH Character and not the number of things in Array.

Where am I going wrong? I am trying to store an Array in a Cookie and then retrive it and save it in an Array.

MrDarkness96
  • 57
  • 2
  • 13
  • Duplicate of [I want to store Javascript array as a Cookie](https://stackoverflow.com/questions/2980143/i-want-to-store-javascript-array-as-a-cookie) – DonJoe Apr 18 '18 at 23:26
  • I have already tried his way but it doesn't seem to work for me – MrDarkness96 Apr 18 '18 at 23:27
  • 1
    Well, change your code, encode the array as string then we can have a look – DonJoe Apr 18 '18 at 23:28
  • If you are converting then array to json and still your code doesn't work, then you are probably hitting the 4k max length of cookies and should keep track of the array at server side. – Xaqron Apr 18 '18 at 23:32
  • 1
    Ok my bad I think last time I tried something went wrong, seems to be wroking with JSON again. Thanks anyway for letting me know that this is only possible with JSON, I'm new to this and didn't know that I can't just store Arrays. – MrDarkness96 Apr 18 '18 at 23:35
  • You could also use `localStorage`, which has much higher limits than cookies. – Barmar Apr 19 '18 at 00:09

2 Answers2

1

Cookies can stores only string. You need to make a JSON of the array and assign the jsoned string to the cookie

Davide
  • 1,931
  • 2
  • 19
  • 39
0

You probably want to do something like:

localStorage.stuff = JSON.stringify(['a', 'b', 2]);
console.log(JSON.parse(localStorage.stuff));
StackSlave
  • 10,613
  • 2
  • 18
  • 35