Oct 5, 2009

Function to write the cookies in the browser for infinite time in javascript

in this post our objective is to write the cookies through javascript for infinite time period(here we have given the time period as 100 days)ie.cookies never expires.In this javascript we have also accessed the textbox value and SPContext.Current.Web.CurrentUser.LoginName value .
Write this function inside the "Script" tag of the javascript.
------------------------------------------------------


 function WriteCookies() {
//This is the way to access the value of controls in aspx page through javascript      
 var chk = ddocument.getElementById(<% SPHttpUtility.AddQuote(SPHttpUtility.NoEncode(txtBox.ClientID),Response.Output); %>);


//Way to access the current logged in user name from SPContext in javascript
        var userLoginName =<% SPHttpUtility.AddQuote(SPHttpUtility.NoEncode(SPContext.Current.Web.CurrentUser.LoginName),Response.Output); %>;
        if(chk!=null) {
            if (chk.checked) {
                value = 'TRUE';
            } else {
                value = 'FALSE';
            }
            name = 'KeyName'+'_'+userLoginName;
            //To make the expiry if cookie as infinite
            //Currently we have set the expiry date for 100 days.
            var days = 100;
            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=/";
        }
    }
-----------------------------------------------------
So your job is done
Enjoy!!!

No comments:

Post a Comment