We build your ideas. Contact us for Mobile/Web App Development. Write us @ contact@milanjeet.com

Understanding cookies in JavaScript: Set, get and delete with Example

JavaScript Cookies

Cookies are piece of data stored in client’s machine to remember the user’s information for better user experience and site statistics. We all use cookies knowingly / unknowingly. You might have seen sometimes after creating an account with a site, we do not have to remember and type the password again and again. This is what the magic of cookies. Cookies remembers user information. Cookies are small text files and stores data in key=value pair. In this post we are going to learn about the cookie in javascript what exactly it is.

Cookies are the part of Web Storage in Javascript. These are small text files which keep the data in key=value pair.

Why do we need a cookie?

To avoid the communication between browser and server to small data each time, cookies are user. Stateless Protocol HTTP is used to communicate between server and client. Each request treated independently during this, so after sending the data from the server, the connection is shut and server does not keep the data.

localStorage and sessionStorage in Javascript are also used to store the user data but there is a difference. Click the above link to know the difference.

Users are keep visiting the sites and we also visit forums again and again to get the solution of a problem.Similarly, sometimes server needs data again to verify user’s information. That’s where cookies are really helpful. Without having to communicate to/from the browser, cookies are accessed from the computer/machine itself.

Creating a cookie in Javascript

We create cookie using document object with the property cookie as below.

document.cookie = "cookie_name=cookie_value"

Cookie can expire automatically or programatically, expire property is used to do so.

document.cookie = "cookie_name=cookie_value; expires=date"

Example

function jQueryProSetCookie(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=/";
}
What example says:

The above function has 3 parameter which are nothing but cookie name, cookie value and cookie expiration date. document.cookie is used to set the cookie.

Get Cookie

To get cookie, we have to fetch all cookies, in another words, we have to fetch cookies from document.cookie  and split with semicolon ( ; ). We’ll then compare array values with ours cookie name. If it does exist, we will print.

function jQueryProgetCookie(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 "";
}

now let’s know whether our cookie exist using above example. We have written 2 functions.

first: which sets cookie, another which reads cookie.

jQueryProCookie is called on page load.

function jQueryProCookie() {

    //get cookie using get cookie fn name.
    var username = jQueryProGetCookie("username");

    // check if username empty
    if (username != "") {
        alert("Welcome again " + username);
    } else {
        username = prompt("Please enter your name:", "");
        if (username != "" && username != null) {
            // set cookie
            jQueryProSetCookie("username", username, 365);
        }
    }
}

Delete Cookie in Javascript

If we are setting and getting cookie, then sometime there is a need to delete the cookie as well. We can delete cookie by setting expire parameter to passed date. Deleting a cookie is really simple. Below example demonstrate the same.

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";

Cookie: Watch Video

Leave a Reply

Your email address will not be published. Required fields are marked *

Enjoy this blog? Please spread the word :)