views:

77

answers:

5

I need some help creating the necessary Javascript to add values to an existing cookie. I know how to do it in c#, but it needs to be done in Javascript in this scenario.

This is the C# Code:

HttpCookie myCookie = HttpContext.Current.Request.Cookies["SiteSettings"];
myCookie.Values.Add(varName, varValue);
myCookie.Expires = DateTime.Now.AddYears(1);
HttpContext.Current.Response.Cookies.Add(myCookie);

Can anyone help me convert this to Javascript? I've searched high and low on the internet, and most tutorials don't have a way of specifying the cookie (this site has more than one cookie).

Thank you very much, Andrew

+1  A: 

I believe:

document.cookie= varName + "=" + varValue + ";expires=" + new Date().toUTCString;

That, however, sets the expiration time to now. I don't know how to add a year to it.

James Curran
var d=new Date(); d.setFullYear(d.getFullYear()+1);
no
+2  A: 

Not sure where you've looked, since the first hit on google for "javascript cookies" is this excellent article by ppk: http://www.quirksmode.org/js/cookies.html

It should answer your question and explain other JS-related cookie-nuances, including example functions for handling cookies in a more sensible way than string concatenation.

Jani Hartikainen
A: 

There's some good info on javascript handling of cookies here: http://www.quirksmode.org/js/cookies.html

// from your example

var myCookie = readCookie("SiteSettings");
createCookie(varName, varValue, 365);

// from http://www.quirksmode.org/js/cookies.html

function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else var expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}
no
A: 

I suggest that you take a look at this jQuery plugin: http://plugins.jquery.com/project/cookie. Makes cookie manipulation very easy and it is cross browser safe.

Merrimack
A: 

This will work and will give the desired result

var d = new Date();

document.cookie= varName + "=" + varValue + ";expires=" 
    + new Date((d.getFullYear()+1), d.getMonth(), d.getUTCDate()).toUTCString());

see the article

Javascript - Cookies

Azhar