最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Issue with storing and recalling cookies Javascript - Stack Overflow

programmeradmin2浏览0评论

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;
    }
  }
}

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;
    }
  }
}
Share Improve this question edited Jun 2, 2018 at 9:17 Ivan 40.8k8 gold badges73 silver badges117 bronze badges asked May 28, 2018 at 0:55 JobaliskJobalisk 7281 gold badge6 silver badges17 bronze badges 5
  • 1 Strongly suggest using localStorage rather than cookie for this. Keep in mind that every single request to server (images, css, data, script files, html etc) will have to send that cookie – charlietfl Commented May 28, 2018 at 0:57
  • EOF error huh? cookies don't produce an EOF error - perhaps the load and save cookie functions are rubbish? – Jaromanda X Commented May 28, 2018 at 0:58
  • nope, they function fine, the EOF is what is produced after I try to load the list containing the products. I was looking into local storage, but, correct me if I'm wrong, It doesn't work on older browsers right? – Jobalisk Commented May 28, 2018 at 2:56
  • cookie functions are documented here: stackoverflow./questions/4825683/… – Jobalisk Commented May 28, 2018 at 3:49
  • Ok, I have a different error now, updating this thread. – Jobalisk Commented May 28, 2018 at 23:59
Add a ment  | 

5 Answers 5

Reset to default 5

Use localStorage

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

//Get
var json_str = localStorage.getItem('ProductListCookie');

Would have made a ment, 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?

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.

I think you are defining the function when page.onload occures. If Yes you have to define your function like this:

window.GetProductPrice = function(productIdz){

check this and let me know the result.

Generally speaking, cookies are limited to 4k, so localStorage is better.

发布评论

评论列表(0)

  1. 暂无评论