I'm having trouble setting cookies.

I'm building an online ordering site and it requires multivalued cookies, but my code won't save anything. The cookie is assumed 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;
   } 
}

      

+3


source to share


1 answer


I tried your code in Chrome latest on Windows 7:

setCookie('test', 'test')

      

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

console.log(document.cookie)

      

outputs:



"test=test;....

      

If the code doesn't work on your side, I can assume it was called:

  • Invalid values ​​for other parameters
  • Wednesday (try another browser)

G'luck!

0


source







All Articles