Wednesday, 22 June 2016

Create cookies in javascript without use any third party library.

Create cookies in javascript. Without use any third party library.

function createCookie(name, value, minute) {
    var expires = "";
    if (minute) {
        var date = new Date();
        var minutes = 60;
        date.setTime(date.getTime() + (minute * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
        // date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        // expires = "; expires=" + date.toGMTString();
    }
    else expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

Usage:
var dataToSave = JSON.stringify({id:1,name:"test@gmail.com",role:"admin"});
createCookie('input', dataToSave , 60);


After login for check the cookies:
function checkLogin() {
    var validate = true;
    var cookieValue = readCookie("input");
    if (cookieValue == null) {
        validate = false;
    }
    else {

    }

    if (!validate) {
        //redirect to login
    }

    else {
        setProfile();
    }
}

To get the data from the cookie.
function setProfile() {
    var profileData = parseCookie();
    $("#lnkUserName").text(profileData.email);
}

To read data from cookie and convert that data into json object.
function parseCookie() {
    var dataToParse = document.cookie.split('=')[1];
    return JSON.parse(dataToParse);
}

To read the cookie for check cookie existance.
function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

No comments:

Post a Comment