Hey there! any question in your mind? Ask It Now!.

Popular Categories





how to set cookies in JavaScript

+1 vote
165 views
asked in Programming by mannu (990 points)
I am trying to set cookie in java script but its not happening would you help me?

Using like this :

          document.cookie = "setcookie=false;
          expires=0; path=/; domain=10.0.0.9";

Some how cookie is not setting :(

2 Answers

+2 votes
answered by PRASHANT PATEL (300 points)

Use below funciton

function set_cookie(name, value, expires, path, domain, secure) {
 
if (!domain) {
if (!_this.cookie_domain) {
domain = _this.cookie_domain;
} else {
// use the page domain if none define
domain = document.domain;
}
}
 
var curCookie = name + '=' + value +
((expires) ? '; expires=' + expires.toGMTString() : '') +
((path) ? '; path=' + path : '') +
((domain) ? '; domain=' + domain : '') +
((secure) ? '; secure' : '');
document.cookie = curCookie;
}
commented by jatin Expert (3,823 points)
nice good way to set cookie.
+2 votes
answered by amit_pammu Expert (5,030 points)

Try this . easier way to set the cookies..!!

 

<!DOCTYPE html>
<html>
<head>
<script>
 
function setCookie(cname,cvalue,exdays)
{
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}
 
function getCookie(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) 
  {
  var c = ca[i].trim();
  if (c.indexOf(name)==0) return c.substring(name.length,c.length);
  }
return "";
}
 
function checkCookie()
{
var user=getCookie("username");
if (user!="")
  {
  alert("Welcome again " + user);
  }
else 
  {
  user = prompt("Please enter your name:","");
  if (user!="" && user!=null)
    {
    setCookie("username",user,30);
    }
  }
}
 
</script>
</head>
<body onload="checkCookie()">
</body>
</html>
 

Related Questions

+6 votes
1 answer 248 views
+1 vote
1 answer 154 views
+1 vote
1 answer 256 views
+5 votes
2 answers 1,169 views
0 votes
1 answer 112 views
+4 votes
5 answers 2,481 views
+1 vote
1 answer 746 views
+3 votes
1 answer 576 views
+4 votes
3 answers 916 views

Not a Member yet?

Ask to Folks Login

My Account
682 Folks are online
1 members and 681 guest online
Your feedback is highly appreciated