Thursday, October 2, 2008

How to use Cookies in web applications?

Cookies are similar to variables but stored at client side (browser), helps in executing light weight functionalities instead of pinging the server.

Example:-
We use a cookie flag which helps in identifying whether the user has logged in or logged out. If user log out from the application, then he cannot click on back button at the top of the browser to reload the previous application page.


I shall check out in the page load of application page, the value of cookie. If it says that user has logged out then I shall redirect to login page else continue loading the page.

Function to add cookies.
function AddCookie(cName,cValue)
{
document.cookie=cName+"="+cValue+"; path=/";
}

document.cookie indicates that the cookie should be added to current document.
Cname the parameter plays a role as key and stores the cvalue received in the function.Where as “path/” indicates the availability or accessbility of the cookie added.
If Path says “/” then it mean that cookie varaible can be access in the whole application else only in that specific page.
Also we have attribute called “Expiry” which terminates the cookie at specific time interval after creation.

Function to retrieve value from document cookies based on cookie name (Key)

function GetCookieValue(cName)
{
var allcks=document.cookie;
var cks=allcks.split(";");
for(var i=0;i<cks.length;i++)
{
var cok=cks[i];
while(cok.charAt(0)==" ")
{
cok=cok.substring(1,cok.length);
}
if(cok.indexOf(cName)==0)
{
var val=cok.substring(cName.length+1,allcks.length);
return val;
}
}
return " ";
}

Since there can be multiple cookies at an instant for a document, we should split those cookies with “;” and again retrieve the cookie name from each splitted cookie.

If the name sent matches with the cookie then retrieving the cookie value and returning it.


Application Page
function CheckForLogin()
{
var val=GetCookieValue("Login");
if(val!='y')
{
location.href="../Login.aspx";
}
}


I shall place the above fnction in “onload” event of body in the application page to check before loading.
<body onload=" CheckForLogin ();”>
If the flag says that user has not logged in then redirecting to login page.



Login Page
function RemoveLogin()
{
AddCookie("Login","n");
}

<body onload="RemoveLogin();">
In the same fashion in “onload” event of login page I shall addcookie with flag saying that User has logged it.


User clicking on Login button

function AddLogin()
{
AddCookie("Login","y");
}


As soon as user log in’s into application clicking on “Login” button I shall again add cookie satting login flag as user has logged in.
Calling the above javascript function on click evet of login button.

No comments: