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?
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 $.
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);
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: '/' });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With