3

Im making a mock online ordering site and it requires multivalued cookies but my code wont save anything. The cookie is supposed to contain the product name, price, and quantity. Any help would be appreciated.

function setCookie(cName, cValue, expDate, cPath, cDomain, cSecure) {
   if (cName && cValue != "") {
      var cString = cName + "=" + escape(cValue);
      cString += (expDate ? ";expires=" + expDate.toGMTString(): "");
      cString += (cPath ? ";path=" + cPath : "");
      cString += (cDomain ? ";domain=" + cDomain : "");
      cString += (cSecure ? ";secure" : "");
      document.cookie = cString;
   }
}

function setField(cName, fName, fValue, expDate, cPath, cDomain, cSecure) {

   if (cName  && fName  && fValue != "") {

      var subkey = fName + "=" + escape(fValue);

      var cValue = null;
      var cookies = document.cookie.split("; ");
      for (var i = 0; i < cookies.length; i++) {
         if (cookies[i].split("=")[0] ==  cName) {
            cValue = cookies[i].slice(cookies[i].indexOf("=") + 1);
            break;
         }
      }
     if (cValue) {
         var foundField = false;
         var subkeys = cValue.split("&");
         for (var i = 0; i < subkeys.length; i++) {
            if (subkeys[i].split("=")[0] == fName) {
               foundField = true;
               subkeys[i] = subkey;
               break;
            }
         }
         if (foundField) cValue = subkeys.join("&")
         else cValue += "&" + subkey;
     } else {
         cValue = subkey;
     }
      var cString = cName + "=" + cValue;
      cString += (expDate ? ";expires=" + expDate.toGMTString(): "");
      cString += (cPath ? ";path=" + cPath : "");
      cString += (cDomain ? ";domain=" + cDomain : "");
      cString += (cSecure ? ";secure" : "");
      document.cookie = cString;
   } 
}
MagMurph
  • 39
  • 3
  • try jquery-cookie library.easy way to read write cookies. How to use: http://stackoverflow.com/questions/1458724/how-to-set-unset-cookie-with-jquery Using Multivalue Cookies: http://stackoverflow.com/questions/6417140/jquery-cookie-plugin-multiple-values – Deshan Dec 11 '14 at 10:16

1 Answers1

0

I tried your code in Chrome latest in Windows 7:

setCookie('test', 'test')

and it works as expected, cookies with this name and value is being set:

console.log(document.cookie)

outputs:

"test=test;....

If the code doesn't work on your side I can assume it is caused by:

  • Wrong values for other params
  • Environment(try the other browser)

G'luck!

etual
  • 561
  • 1
  • 4
  • 13