How can I work with cookies with JS or jQuery?

-4

I need to create, read and delete cookies from the client side, for this I need to use javascript or jQuery but I do not know how to manipulate the cookies from here, there is a framework that helps with this issue or I have to build my own functions in javascript to create, read and delete a cookie?

    
asked by vcasas 04.07.2018 в 23:25
source

1 answer

0

I leave this link, I hope it serves you link

Here you can see the code:

 //función para crear la cookie
function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

//función para leer la cookie
function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

//función para validar una cookie

function checkCookie() {
    var user = getCookie("username");
    if (user != "") {
        alert("Welcome again " + user);
    } else {
        user = prompt("Please enter your name:", "");
        if (user != "" && user != null) {
            setCookie("username", user, 365);
        }
    }
}
    
answered by 04.07.2018 в 23:33