Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with storing and recalling cookies Javascript

So, I'm trying to save and load a cookie that contains a list of product details and then display these product details to the page.

However when I run this what I receive is a

ReferenceError: Can't find variable: GetProductPrice

when trying to read the cookies I stored using the GetProductPrice() function.

The cookie storer runs when the website loads for the first time. It creates a list of products which I later intend to use as part of a shopping cart. It then should save this cookie so that it can be accessed again if the user goes to a different page. This way if the user adds an item to the cart, the carts variables won't be later reset. However as I said before, this doesn't work. The load and save cookie functions are created by someone else on Stack Overflow and work fine.

Here is the code for the cookie saver that should run only the first time the user accesses the site:

function setUpProducts() { //in here we define each of the products when we first start up. This way we know what products the customer has access to.
  setUpPages();
  try {
    hasRun = getCookie('hasRunCookie'); //get the has run cookie from before, or at least try to
  } catch {
    hasRun = 0;
  }
  //if (hasRun != 1){ //only run this the first time, otherwise we dont need to.
  if (hasRun != 1) {
    hasRun = 1;
    createCookie('hasRunCookie', hasRun);
    var dataList = []; //array for holding the raw data
    var nameList = [];
    var priceList = [];
    var amountList = []; //lists for temporrily holding data before it is put in the product list's product objects.
    var set1 = 0; //allows differentiating between different values in the raw data
    var productIds = 0; //product ID to differentiate between products easily

    $.get('../productdata.txt', function(data) { //the text file product data contains all the product infomation so that it can be changed at a moments notice.
      //var fileDom = $(data);

      dataList = data.split("\n");
      $.each(dataList, function(n, elem) {
        $('#myid').append('<div>' + elem + '</div>');
      });
    });

    var i;
    for (i = 0; i < dataList.length; i++) { //this gets the infomation from the text file and loads it into the products
      if (set1 == 0) {
        nameList.push(dataList[i]);
        set1 = 1;
      } else if (set1 == 1) {
        priceList.push(dataList[i]);
        set1 = 0;
      }
    }
    while (productIds != 8) { //make the products, programing counting always starts at 0, so 8 is actually the 9th number.
      var productObject = {
        productID: productIds,
        productName: nameList[productIds],
        productPrice: priceList[productIds],
        purchasedAmount: 0
      };
      productList.push(productObject); //put each product into the product list.
      productIds += 1;
    }
    var json_str = JSON.stringify(productList); //bottle and store our list of products
    createCookie('ProductListCookie', json_str);
    //}

  }

Here is the code used to load the cookie and display a product's price on the relevant product page:

function GetProductPrice(productIdz) {
  var json_str = getCookie('hasRunCookie');
  productList = JSON.parse(json_str);
  for (i = 0; i < productList.length; i++) {
    if (productList[i].productID == productIdz) {
      productHolder = productList[i];
      document.getElementById("price").innerHTML = productHolder.productPrice;
    }
  }
}
like image 340
Jobalisk Avatar asked May 28 '18 00:05

Jobalisk


People also ask

Can JavaScript manipulate cookies?

JavaScript can also manipulate cookies using the cookie property of the Document object. JavaScript can read, create, modify, and delete the cookies that apply to the current web page.

Which is better localStorage or cookie?

Cookies are intended to be read by the server, whereas localStorage can only be read by the browser. Thus, cookies are restricted to small data volumes, while localStorage can store more data.

What is persistent cookies in JavaScript?

Persistent cookiePersistent cookies are not deleted by the browser when the user closes it. These cookies have an expiration date that you can set in your server. You can set a cookie to expire in a day or ten years.


3 Answers

Use localStorage

//Set
localStorage.setItem('ProductListCookie', json_str);

//Get
var json_str = localStorage.getItem('ProductListCookie');
like image 104
ssten Avatar answered Nov 05 '22 01:11

ssten


Would have made a comment, but can not.

First, if you get: ReferenceError: Can't find variable: GetProductPrice, it might be that your GetProductPrice function is not defined in that page, or maybe not yet, check the loading order of your scripts.

Second:

function GetProductPrice(productIdz){
  var json_str = getCookie('hasRunCookie'); // this is 1
  productList = JSON.parse(json_str) // this also is 1

maybe

getCookie('ProductListCookie')

would work?

like image 30
lucchi Avatar answered Nov 04 '22 23:11

lucchi


As others have mentioned ReferenceError: Can't find variable: GetProductPrice means that JS simply can't find your function. Make sure the code that calls GetProductPrice() can access the function.

On a separate note – you shouldn't use cookies for this. Cookies are sent to the server with each request and are going to increase the load on your server and slow down the page load for users.

For your purposes consider using localStorage, it is supported by all modern browsers and even IE 8+, and does everything you need without the overhead of sending unnecessary info to the server. And you will barely need to change your code.

like image 1
Minderov Avatar answered Nov 05 '22 01:11

Minderov