Sometimes we need to store session information for different web pages. It is mostly needed for commercial websites where we need to fill up a form through several stages. So to maintain the session information across web pages and to keep track of statistics of the site.
Data is send to the visitor’s browser by the server in the form of a cookie. This is stored as a plain text record on the visitor’s hard drive. Now the same cookie is send to the server for data retrieval when the visitor visits another page on that site.
Cookies are records defined by 5 variable length fields:
1. Expires:
The expiration date of the cookie. If this is blank, the cookie will expire when the visitor quits the browser.
2. Domain:
The domain name of your site. It basically tells to which domain the cookie should be sent.
3. Path:
The path to the directory or web page that set the cookie.
4. Secure:
the cookie may only be retrieved with a secure server If this field contains the word "secure"
5. Name=Value:
Cookies are set and retrieved in the form of key-value pairs separated by semi-colons.
Code example to store and read a cookie :-
Cookies are accessible through the property document.cookie.
<html>
<head>
<script type="text/javascript">
function storeCookie()
{
if( document.newform.employee.value == "" ){
console.log ("Enter store!);
return;
}
cookievalue= escape(document.newform.employee.value) + ";";
document.cookie="name=" + cookievalue;
document.write ("Cookies stored : " + "name=" + cookievalue );
}
function ReadCookie()
{
var getcookies = document.cookie;
document.write ("All Cookies : " + getcookies )
;
// Get all the cookies pairs in an array
cookieData = getcookies.split(';');
// Now take key value pair out of this array
for(var i=0; i<cookieData.length; i++){
name = cookieData[i].split('=')[0];
value = cookieData[i].split('=')[1];
document.write ("Key is : " + name + " and Value is : " + value);
}
}
</script>
</head>
<body>
<form name=newform" action="">
<input type="button" value=Store Cookie" onclick="storeCookie()"/>
<input type="button" value="Get Cookie" onclick="ReadCookie()"/>
</form>
</body>
</html>
The above code sets a employee name in an input cookie and read it (or retrieved) by key-value pairs.
0 Comment(s)