0

I want to create cookie on root of my host. for example when i'm on www.mydomain.com/test and set cookie , it creates on the cookie on the root. i tried jquery cookie plugin and this function but it don't work:

function setCookie2(c_name, value, expiredays) {
$.cookie(c_name, value, {
    expires: 1,           //expires in 10 days

    path: '/'          //The value of the path attribute of the cookie 
    //(default: path of page that created the cookie).
});}

it still creates cookie on /test folder

Alia
  • 28
  • 5
  • Take a look at this topic: http://stackoverflow.com/questions/1458724/how-to-set-unset-cookie-with-jquery. The comments include links to resources that you need. –  Aug 24 '13 at 09:19

1 Answers1

2

Don't ask me why, but I always encountered problems by managing cookies using any kind of plugin most often your problems are around the plugin not loaded or a jQuery version mismatch, as extra the $.cookie plugin is no longer maintained now, so likely you are encurring in a bug.

So, document.cookie is your friend, not only because you don't need any libraries for that, but even because it's more semantic than the jQuery counterpart.

In your example you might want to do something like this, to set the expiration in the next 10 days.

const expiration = new Date();
expiration.setDate(expiration.getDate() + 10);
expiration.toUTCString();
document.cookie = `NAME=VALUE; expires=${expiration}; path=/`;

You can slap this in a function so you can call that multiple times, if you need to set up different cookies.

const setcookie = (name: string = "", value: string = "", days: number = 1) => {
    if (name === "") {
        throw new Error("Cookie name cannot be empty");
    }
    const expiration = new Date();
    expiration.setDate(expiration.getDate() + days);
    expiration.toUTCString();
    document.cookie = `${name}=${value}; expires=${expiration}; path=/`;
}
setcookie("NAME", "VALUE", 10);
MacK
  • 2,132
  • 21
  • 29