waterschaats
waterschaats

Reputation: 994

jQuery Cookie path

I use the jQuery cookie plugin for storing cookies, with the following code I can save a Cookie for 7 days, but it only saves it for the page its created on. I want the cookie to be available for the whole website.

$.cookie('basket',basket,{ expires: 7 });

I tried to set a path, but that didn't seem to work

$.cookie('basket',basket,{ expires: 7, path:'/' });

full code: this works fine, but it only saves the cookie for the current page

function add_to_basket(id,title){
if($.cookie('basket')){
    basket=$.cookie('basket');

    var basket_array = basket.split(',');

    var index = jQuery.inArray(id,basket_array);
    if(index > -1){
        return false;
    }else{
        basket+=','+id;
        $.cookie('basket',basket,{ expires: 7 });
    }
}else{

    basket=id;
    console.log(basket);
    $.cookie('basket',basket,{ expires: 7 });

}

Upvotes: 37

Views: 50857

Answers (5)

Jeetendra Negi
Jeetendra Negi

Reputation: 453

use this

$.cookie('basket', value, { path: '/' });

Upvotes: 0

zzmaster
zzmaster

Reputation: 317

I don't think that patching plugin's body is a nice idea. Sadly plugin is not configurable.. I use wrapper function:

$.cookie2 = function(key, value, options)
{
    if (typeof value!='undefined')
    { // setting cookie
        var defaults = {expires: 180, path:'/'};
        $.extend(defaults, options || {});
        return $.cookie(key, value, defaults);
    }
    // getting cookie
    return $.cookie(key, value, options);
}

Usage:

// set with defaults defined in wrapper
$.cookie2('name', 'value');

// rewrite defaults or add something
$.cookie2('name', 'value', {expires: 1, something: 'else'}); 

Upvotes: 1

Dimitar Stanimirov
Dimitar Stanimirov

Reputation: 11

I had the same problem but I found that this occurs only when I minify the jquery.cookie.js and when I put in

config.defaults = {expires: 180, path:'/', domain: '.domain.com' };

it sets the cookie path to '/', whatever internal page is loaded, e.g., yourdomain.com/en/page1/page - cookie path = '/'

Upvotes: 1

Tim Santeford
Tim Santeford

Reputation: 28111

I just had the same problem. I fixed it by always specifying the path when writing the cookie.

$.cookie('basket', value, { path: '/' })

This is an issue with the jquery cookie plugin. It will default to the path of the current page.

Upvotes: 60

bitlove
bitlove

Reputation: 179

In the plugin file change:

config.defaults = {};

to

config.defaults = {path:'/'};

from https://github.com/carhartl/jquery-cookie/issues/2#issuecomment-790288

Upvotes: 16

Related Questions