user319854
user319854

Reputation: 4096

How to delete a cookie using jQuery?

I want to use jQuery to delete cookies; I have tried this:

$.cookie('name', '', { expires: -1 });

But when I refresh the page, the cookie is still there:

alert('name:' +$.cookie('name'));

Why?

Upvotes: 104

Views: 254354

Answers (8)

Zoli Incze
Zoli Incze

Reputation: 1

Actually the second part of the accepted answer is OK only for some cases, it depends on the js-cookie version that you have.

So either use js-cookie v1.5.1 $.removeCookie ($.cookie for other operations), or if you are using 2.0.0 or higher, the old APIs were changed to Cookies.remove (Cookies.set, Cookies.get, etc.)

I found a complete answer here.

Upvotes: 0

Chadwick
Chadwick

Reputation: 12663

To delete a cookie with JQuery, set the value to null:

$.cookie("name", null, { path: '/' });

Edit: The final solution was to explicitly specify the path property whenever accessing the cookie, because the OP accesses the cookie from multiple pages in different directories, and thus the default paths were different (this was not described in the original question). The solution was discovered in discussion below, which explains why this answer was accepted - despite not being correct.

For some versions jQ cookie the solution above will set the cookie to string null. Thus not removing the cookie. Use the code as suggested below instead.

$.removeCookie('the_cookie', { path: '/' });

Upvotes: 162

Jan Richter
Jan Richter

Reputation: 2076

You can also delete cookies without using jquery.cookie plugin:

document.cookie = 'NAMEOFYOURCOOKIE' + '=; expires=Thu, 01-Jan-70 00:00:01 GMT;';

Upvotes: 16

aularon
aularon

Reputation: 11110

What you are doing is correct, the problem is somewhere else, e.g. the cookie is being set again somehow on refresh.

Upvotes: -3

Gert-Jan Rebel
Gert-Jan Rebel

Reputation: 761

You can try this:

$.removeCookie('the_cookie', { path: '/' });

source: https://github.com/carhartl/jquery-cookie#readme

Upvotes: 76

Andron
Andron

Reputation: 6621

Worked for me only when path was set, i.e.:

$.cookie('name', null, {path:'/'})

Upvotes: 0

Otto Kanellis
Otto Kanellis

Reputation: 3708

Try this

 $.cookie('_cookieName', null, { path: '/' });

The { path: '/' } do the job for you

Upvotes: 1

logan kim
logan kim

Reputation: 41

it is the problem of misunderstand of cookie. Browsers recognize cookie values for not just keys also compare the options path & domain. So Browsers recognize different value which cookie values that key is 'name' with server setting option(path='/'; domain='mydomain.com') and key is 'name' with no option.

Upvotes: 4

Related Questions