Create Cookie in Javascript

Introductions 


In this article I will show you how to create a cookie in JavaScript. Its very simple and you may need this for various purposes. I came across a problem where I need to solve the problem using cookie so I have tried this one.


Behind The Scene 


First of all you have to create a .html page ( you can do this in .aspx page ) also. But here in the example I will be showing you this through a html page.

Now take a button in the HTML page and call a JavaScript function"checkCookie()" on its onclick function.
 <input type="button" value="Click Me" onclick="checkCookie()" /> 
 Now go to the head section and define the  checkCookie() method there.
 function checkCookie() {
        var username = getCookie("username");
        if (username != null && username != "") {
            alert("Welcome again " + username);
        }
        else {
            username = prompt("Please enter your name:", "");
            if (username != null && username != "") {
                setCookie("username", username, 365);
            }
        }
    }
Here we are checking if the cookie named "username" exists or not. if exists then show an alert with the cookie name and if not then show a prompt where you can add the name in the textbox and that will be stored in cookie.

For geting the cookie it calls the getCookie() method.
 var username = getCookie("username");
Let's define the  getCookie() method.
 
function getCookie(c_name) {
        var c_value = document.cookie;
        var c_start = c_value.indexOf(" " + c_name + "=");
        if (c_start == -1) {
            c_start = c_value.indexOf(c_name + "=");
        }
        if (c_start == -1) {
            c_value = null;
        }
        else {
            c_start = c_value.indexOf("=", c_start) + 1;
            var c_end = c_value.indexOf(";", c_start);
            if (c_end == -1) {
                c_end = c_value.length;
            }
            c_value = unescape(c_value.substring(c_start, c_end));
        }
        return c_value;
    }
 
In this method we are checking if the cookie named username exists or not if yes the return the value.

Now if not exists then we are calling the setCookie()  method bellow for setting the cookie value.

Here we are calling the "setCookie()"  method. whic takes 3 parameters the cookie name its value from the textbox and the time period upto which the cookie will be active.
setCookie("username", username, 365);
Now define the setCookie() method.
 
function setCookie(c_name, value, exdays) {
        var exdate = new Date();
        exdate.setDate(exdate.getDate() + exdays);
        var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" 
                                          + exdate.toUTCString());
        document.cookie = c_name + "=" + c_value;
    }
 
Now you are done with the coding part just go and open the html page in the browser and see what happens.

Happy Codding...

No comments:

Post a Comment