Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 390
user319854 Avatar asked Sep 08 '10 20:09

user319854


People also ask

How to remove a cookie jQuery?

Delete (Remove) Cookies in jQuery cookie function. The $. cookie function accepts two parameters, first the Name (Key) of the Cookie and second the Value to be stored in the Cookie. When the Delete Cookie Button is clicked, the respective jQuery event handler is executed which removes the Cookie using the $.

How do I get rid of cookies?

To unset a cookie, you have to use setcookie() function as well. Just set the expiration time to be someday in the past, and the cookie will be considered unset or deleted, something like this as your second method indicates: setcookie("key","value",time()-3600);


1 Answers

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: '/' }); 
like image 190
Chadwick Avatar answered Oct 20 '22 21:10

Chadwick