Jobalisk
Jobalisk

Reputation: 728

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

Upvotes: 11

Views: 293

Answers (5)

R.hui
R.hui

Reputation: 523

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

Upvotes: 0

Armin Ghasemi
Armin Ghasemi

Reputation: 381

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.

Upvotes: 0

Minderov
Minderov

Reputation: 521

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.

Upvotes: 1

ssten
ssten

Reputation: 2049

Use localStorage

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

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

Upvotes: 5

lucchi
lucchi

Reputation: 1046

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?

Upvotes: 5

Related Questions