Collecting data stored in Cookies by JavaScript

As cookies are stored as name value pairs so we have to read ( or collect ) first and then apply various string functions to get our data. Some of the string functions we will be using are split, indexOf and substr
To read the cookies stored here is the code.

var str = document.cookie

Now the total string is stored in our variable str. To get the array we will break the string using semi columns ; as delimiter. Here is the combined line to get the array of string.

var my_array=document.cookie.split(";");

Now in our array ( my_array) each element have two parts, one is name of the data and other one is value of the data. This name and value are separated by =. Here is one simple example with two sets of name value pairs separated by a ;

name=Simon; __utma=96992031.1087661074.1323303804.1327898268.1327904038.64;

So to get the data and value part of each element we will try to find out the location of '=' by using indexOf() function and then get the part of the string by using substr() function. The sub string we will get before the = is our name and the string after the = will be our corresponding value ( or data) of the name. To get this here is our sample code.

var my_array=document.cookie.split(";");
for (i=0;i {
var name=my_array[i].substr(0,my_array[i].indexOf("="),my_array[i]);
var value=my_array[i].substr(my_array[i].indexOf("=")+1);
if(name==my_data){
return value;
}
}

Since we will have several name and value pairs, we will use one if condition to check our required name and then collect the corresponding value. To do all these we will use one function which will take name of the cookie and return the associated value of it. Here is the complete code to read the cookies values.

<html>
<head>
<script type="text/javascript">
function read_cookies(my_data){
document.write(document.cookie);
document.write("<br><br>");
var my_array=document.cookie.split(";");
for (i=0;i<my_array.length;i++)
{
//document.write(my_array[i] + "<br >");
var name=my_array[i].substr(0,my_array[i].indexOf("="),my_array[i]);
var value=my_array[i].substr(my_array[i].indexOf("=")+1);
//document.write( name + " : " + value + "<br>");
if(name==my_data){
return value;
}
}

}

document.write("Welcome " + read_cookies("name"));
</script>
</head>
<body>

<br><br>
<a href=add-cookies.htm>Add Cookies</a> | <a href=read-cookies.htm>Read Cookies</a> | <a href=delete-cookies.htm>Delete Cookies</a>
</body>
</html>



plus2net.com




Post your comments , suggestion , error , requirements etc here .




We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
©2000-2020 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer