1

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

2
  • Your setCookie does not return a value so you can not call it in alert Commented Jan 29, 2015 at 8:27
  • your function is set_cookie not setCookie. Commented Jan 29, 2015 at 8:28

2 Answers 2

1

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>
Sign up to request clarification or add additional context in comments.

Comments

0

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.

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.