0

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

5 Answers 5

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

var d=new Date(); d.setFullYear(d.getFullYear()+1);
1

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

Comments

1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.