Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
46
rated 0 times [  49] [ 3]  / answers: 1 / hits: 16711  / 12 Years ago, thu, march 29, 2012, 12:00:00

I am working on an online shop together with my friend. He set a cookie for me with PHP with the amount of added products to the Cart. The cookie is called cart, and the variable with the amount of the products is called items.



And I have to read the cookie and get the value of cart back with javascript and print it in the HTML document, but I have no Idea how to use it, can you please help me? I have never worked with cookies or JSON before, but I think it should be done with JSON, can you please explain it to me how it works?



when I do : console.log(document.cookie);



I receive something like this: cart=%7B%22items%22%3A%7B%228%22%3A1%7D%7D;



And I have no idea how to encode it.



Thank you


More From » jquery

 Answers
15

That is the URL encoded equivalent of {items:{8:1}} which is the JSON string you want.



All you have to do is decode it and parse the JSON:



var cart = JSON.parse(decodeURIComponent(document.cookie.cart));


Then logging cart should give you an object with an 'items' property that you can access as needed.



EDIT:



As an example, here's a way to iterate through the items and determine the total number of items and the total of all their quantities.



var items_total = 0,
quantity_total = 0;
for (var prop in cart.items) {
items_total += 1;
quantity_total += cart.items[prop];
}

console.log(Total Items: + items_total);
console.log(Total Quantities: + quantity_total);

[#86534] Wednesday, March 28, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
reedmustafam

Total Points: 211
Total Questions: 83
Total Answers: 105

Location: Vanuatu
Member since Wed, Oct 14, 2020
4 Years ago
;