Save and get data from Cookie in NETGEM STB SDK
Posted By : Deepak Gupta | 07-Feb-2014
Save and get data from Cookie
Hello guys ,In this blog I tell you how to save data that are come from form from custom class and also give time when to expire cookie data.And also get data for validation each time when user login between cookie expire time.Step to Save and get data from Cookie is given below:-
first of all I show you my form -:.
Fill the form press ok.
Code for save and validate form is given below-:
Validation of the form
MyClass2.prototype.validateInputs = function validateInputs() { var widgets = this.widgets, userNameInput = widgets.userNameInput; if (userNameInput.getData() === '') { statusMessage.add('Email is a required field. Please go to http://www.oodlestechnologies.com/blogs to register.'); //That is a alert type message this.setInputFocus(userNameInput); //our manual function for the focus on field return false; }; var passwordInput = widgets.passwordInput; if (passwordInput.getData() === '') { statusMessage.add('Password is a required field. Go to http://www.oodlestechnologies.com/blogs to register or set new password.'); //That is a alert type message this.setInputFocus(passwordInput); //our manual function for the focus on field return false; } else if (passwordInput.getData().length<6) { statusMessage.add('Password must have 6 or more characters, contain a number and is case sensitive.'); //That is a alert type message this.setInputFocus(passwordInput); //our manual function for the focus on field return false; }; return true; };
Through getData(){inbuilt function} method we get the value from form that you filled
Code for the setInutFocus() function
MyClass2.prototype.setInputFocus = function setInputFocus(newInput) { var widgets = this.widgets, oldInput = this._lastFocusedInput; if (newInput === oldInput) return; if (oldInput) { oldInput.setFocus(false);//inbuilt function this._lastFocusedInput = null; } newInput.setFocus(true); this._lastFocusedInput = newInput; };
Check whethere it is new user and old
MyClass2.prototype.processLogin = function processLogin(urlForExtendedInformation, type, pass) { var status; var extendedData; var xhr = XMLHttpRequest(); //create an xml parsing object from server if (urlForExtendedInformation == "http://www.oodlestechnologies.com/blogs") { xhr.open("POST", urlForExtendedInformation, false); //take or put data as post method xhr.setRequestHeader("Content-Length", 0); //set the header of the request that you made } else xhr.open("GET", urlForExtendedInformation, false); if (type == "secure") { pass = Base64.encode(pass); //our manual func. for encoding password(optional) NGM.trace("password is------" + pass); //That is used for the make log or bugging xhr.setRequestHeader("Authorization", "Basic " + pass); NGM.trace("Request header set"); } xhr.onreadystatechange = function() { NGM.trace("xhr.readyState " + xhr.readyState); if (xhr.readyState != 4){ return; } extendedData = xhr.responseObject; status = xhr.status; //it return the status of the page found or not NGM.trace("xhr.statusText " + xhr.statusText); xhr = null; }; try { xhr.send(null); } catch(e) { NGM.trace("Request Failed"); } if (status == 200){ return extendedData; } };
xhr.open() function ==>open the page according to url with method type xhr.status;==>it return the status of the page found or not
code for encoding pass
var Base64 = { // private property _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", // public method for encoding encode : function (input) { var output = ""; var chr1, chr2, chr3, enc1, enc2, enc3, enc4; var i = 0; input = Base64._utf8_encode(input); while (i < input.length) { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); } return output; }, // private method for UTF-8 encoding _utf8_encode : function (string) { string = string.replace(/\n\r/g,"\n"); var utftext = ""; for (var n = 0; n < string.length; n++) { var c = string.charCodeAt(n); if (c < 128) { utftext += String.fromCharCode(c); } else if((c > 127) && (c < 2048)) { utftext += String.fromCharCode((c >> 6) | 192); utftext += String.fromCharCode((c & 63) | 128); } else { utftext += String.fromCharCode((c >> 12) | 224); utftext += String.fromCharCode(((c >> 6) & 63) | 128); utftext += String.fromCharCode((c & 63) | 128); } } return utftext; }, };
Above code first encode the string after that another function decoding the encode code .It uses own logic to encode the string
Save in Cookie
this.validateInputs(); if(this.validateInputs()==true){ var url="http://www.oodlestechnologies.com/blogs";//as eg. var widgets = this.widgets; var password=widgets.passwordInput.getData(); var username=widgets.userNameInput.getData(); var cookieExpireDate = new Date(); cookieExpireDate.setMonth(cookieExpireDate.getMonth() + 12); //Get the month through new Date(). Class increase the month by the 12 var userAccountdetail=this.processLogin(url,"secure",username+":"+password); var userAccountdetail=this.processLogin(url,"secure",username+":"+password); //check it is register user or not if(userAccountdetail==null) statusMessage.add("Email or password is incorrect. For help or to register go to http://saffdemo.cloudapp.net"); else{ var firstName=userAccountdetail.getElementsByTagName("FirstName")[0].firstChild.nodeValue; //here it get the value by the node name var lastName=userAccountdetail.getElementsByTagName("LastName")[0].firstChild.nodeValue; //here it get the value by the node name var email=userAccountdetail.getElementsByTagName("Email")[0].firstChild.nodeValue; NGM.trace("firstName " + firstName);
document.cookie="email="+email+",password="+password+"; expires="+ cookieExpireDate.toGMTString() + ";"; //line to save data in cookie statusMessage.add("Hello "+firstName); this.formClose("formClose"); //we can pass any String } }
Get Data from Cookie
function getCookie(c_name) { //parameter to get value from cookie that you pass var i, x, y, ARRcookies = document.cookie.split(","); //all value in the cookie are seperated by (,)comma for ( i = 0; i < ARRcookies.length; i++) { if (ARRcookies[i].search("email") != -1) { x = ARRcookies[0].substr(ARRcookies[0].lastIndexOf("=") + 1); } if (ARRcookies[ARRcookies.length - 1].indexOf(";") != -1){ NGM.trace("Inside if"); y = ARRcookies[ARRcookies.length - 1].substr(ARRcookies[ARRcookies.length - 1].indexOf("=") + 1, ARRcookies[ARRcookies.length - 1].indexOf(";") - 9); } else{ y = ARRcookies[ARRcookies.length - 1].substr(ARRcookies[ARRcookies.length - 1].indexOf("=") + 1); } if (c_name == "email") return unescape(x); else return unescape(y); } }
document.cookie.split(",")==> get the data which saved in the cookie and split by the comma operator ARRcookies[i].search("email") != -1 ===>return -1 if email is not found in the array The deprecated unescape() method computes a new string in which hexadecimal escape sequences are replaced with the character that it represents
Thanks Deepak Gupta
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Deepak Gupta
Deepak is a bright Groovy and Grails developer