pallavidestiny22
pallavidestiny22

Reputation: 335

Setting multiple cookie in javascript

I'm trying to set multiple cookies in document.cookie, but unfortunately my code shows the cookie value as null and undefined. My code is as belows:

<script>
function set_cookie ( name, value, exp_y, exp_m, exp_d, path, domain, secure )
{
  var cookie_string = name + "=" + escape ( value );

  if ( exp_y )
  {
    var expires = new Date ( exp_y, exp_m, exp_d );
    cookie_string += "; expires=" + expires.toGMTString();
  }

  if ( path )
        cookie_string += "; path=" + escape ( path );

  if ( domain )
        cookie_string += "; domain=" + escape ( domain );

  if ( secure )
        cookie_string += "; secure";

  document.cookie = cookie_string;
}
</script>
<script>

alert(setCookie( "username", "Miron" ));
alert(setCookie( "username", "Mirion", 2003, 01, 15 ));
alert(setCookie("username", "John Smith", 2003, 01, 15, "","elated.com", "secure"))
</script>

I technically see no fault in the code. Please tell me where I had gone wrong

Upvotes: 1

Views: 1295

Answers (2)

Rob Wilson
Rob Wilson

Reputation: 1133

It looks like you are trying to call setCookie, but the method you have defined is called set_cookie. If you add a dubugger line in you method and run it - are you hitting the debug statement? To correct, either change the function name to setCookie or change the calls to set_cookie.

Also, the function doesn't seem to return anything, so your alerts will be undefined (when it does run). Once you have made the call to your setCookie method, just try a document.cookie in the console and you should see that your values have been set.

Upvotes: 0

Suchit kumar
Suchit kumar

Reputation: 11859

try to return the string to display in alert and change your function name set_cookie to setCookie.

 <script>
function setCookie ( name, value, exp_y, exp_m, exp_d, path, domain, secure )
{
  var cookie_string = name + "=" + escape ( value );

  if ( exp_y )
  {
    var expires = new Date ( exp_y, exp_m, exp_d );
    cookie_string += "; expires=" + expires.toGMTString();
  }

  if ( path )
        cookie_string += "; path=" + escape ( path );

  if ( domain )
        cookie_string += "; domain=" + escape ( domain );

  if ( secure )
        cookie_string += "; secure";

  document.cookie = cookie_string;
  return cookie_string;//or document.cookie 
}
</script>


 <script>

alert(setCookie( "username", "Miron" ));
alert(setCookie( "username", "Mirion", 2003, 01, 15 ));
alert(setCookie("username", "John Smith", 2003, 01, 15, "","elated.com", "secure"))
</script>

Upvotes: 1

Related Questions