Search code examples
javascriptcookiescookie-path

Set Cookie Path JavaScript


I want the code below to set the path to root, I understand I have to set / as the path value however this is not my code and I am not familiar with Javascript!

function setCookie(name, value, expires, path, domain, secure){

document.cookie= name + "=" + escape(value) +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
}

I have tried editing the code as below but have been unsuccessful.

 setCookie(name, value, expires, path, domain, secure){

document.cookie= name + "=" + escape(value) +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path="/") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
}

Solution

  • change to this

    function setCookie(name, value, expires, path, domain, secure){
        document.cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ("; path=/") +       //you having wrong quote here
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
    }