I am trying to create a shopping cart for anonymous users which are stored in a cookie on the users computer. But I am confused.
Here is my code
$(document).ready(function () {
var PID = $('#Input_Product').val();
var Qty = $('#Input_Qty').val();
var P = $('#Input_Price').val();
var data = { ProductID: PID, Quantity: Qty, Price: P };
$("#btnWrite").click(function () {
// $.cookie("Name", $("#txtName").val());
document.cookie = "Product='+PID+'; expires=Friday, 20 Sep 2019 01:00:00 UTC; path=/ ;";
document.cookie = "Quantity='+Qty+'; expires=Friday, 20 Sep 2019 01:00:00 UTC; path=/;";
document.cookie = "Price='+P+'; expires=Friday, 20 Sep 2019 01:00:00 UTC; path=/;";
});
What I am trying to achieve is get a multi dimensional object array and assign the values of the shopping basket to a cookie or multiple cookies.
Also Being new to javascript, how do I retrieve the values on the client side. I know I can use stringify to post to the server
I tried initializing it with but getting errors
for (var i = 0; i < 1; i++) {
data[i] = new { ProductID: PID, Quantity: Qty };
alert(data[i]);
}
The Cookie Way
Cookie can't store spaces or commas, and you can only store one key-value pair per assignment statement. You could separate each value and assign it to a cookie, like this:
document.cookie = "Product=+PID+;"
document.cookie = "expires=+DATESTRING+;"
document.cookie = "path=+PATH+;"
However, whenever you assign another cookie like this, the previous cookie's path
and expires
will be overwritten. The better way is to encode all the data into a cookie safe string:
document.cookie = "Product=+PID+DATESTRING+PATH+;"
Then you can look up the product and parse each of the arguments using a .split('+')
.
The Modern Way
Cookies have several drawbacks when compared to localStorage. Two of the most impactful being that (1) the cookies in the browser are sent over every http/s request (potential personal information leak) and (2) cookies have a limit of 4KB of data storage, localStorage allows 5MB (significantly more!).
To use it in the way you wanted here, you could do something like this:
// setting it:
localStorage.setItem('Product', '+PID+DATESTRING+PATH+')
// getting it:
const productData = localStorage.getItem('Product').split('+')
const productId = productData[0]
const productDate = productData[1]
const productPath = productData[2]
Hope that helps!