Tuesday, October 1, 2013

Create/Read JavaScript Cookie


Following two methods can be used to create a cookie on the client browser and to read the value of the cookie.

Create Cookie:

name of the cookie, value need to be stored in the cookie and the number of days for cookie expiration are the parameters to be passed when calling the method.

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


Read Cookie:

  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:
Write comments
Recommended Posts × +