Reputation: 867
When a user clicks a link on my page (which has the class deleteCooke
), I want to run a function which deleted two cookies.
The href
itself will control the redirect so just want to delete (or clear) the two cookies.
These two cookies are: lang
and category
.
Here is my current approach:
/* 1. GET CURRENT COOKIE VALUE */
var lang = $.cookie('lang');
var category = $.cookie('category');
/* 2. DELETE FUNCTION*/
function deleteCookies() {
var d = new Date();
d.setTime(d.getTime() - (1000 * 60 * 60 * 24));
var expires = "expires=" + d.toGMTString();
window.document.cookie = lang + "=" + "; " + expires;
window.document.cookie = category + "=" + "; " + expires;
}
/* 3. CALL FUNCTION ON BUTTON CLICK*/
$(document).ready(function() {
$(".deleteLang").click(function() {
deleteCookies();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
<a href="/" class="deleteLang" data-lang="es">Espanyol</a>
However, with this approach, neither of the cookies are being cleared / deleted?
Edit:
How cookie is being set
$.cookie('lang', 'es', {expires: 2, path: '/'});
Current method of removing cookies
$(document).ready(function() {
$(".deleteLang").click(function() {
$.removeCookie('lang', { path: '/' });
$.removeCookie('lang', '', {expires: 2, path: '/'});
$.removeCookie('lang');
});
});
Upvotes: 0
Views: 214
Reputation: 24385
This works as expected.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
<a href="/" class="deleteLang" data-lang="es">Espanyol</a>
$.cookie('lang', 'es', {expires: 2, path: '/'});
$(document).ready(function() {
$(".deleteLang").click(function(e) {
// Prevent navigation.
e.preventDefault();
// Check if the cookie is set
console.log($.cookie('lang'));
// Cookie is removed if 'true' is returned.
console.log($.removeCookie('lang', { path: '/' }));
// Check that cookie is 'undefined'.
console.log($.cookie('lang'));
});
});
If you check the console you'll see:
es
true
undefined
just as expected.
Upvotes: 1