Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

Need to read a cookie value

Posted on 2012-08-20
8
Medium Priority
?
449 Views
Last Modified: 2012-08-22
Hello,

Im looking to read a specific cookie value and then assign the value to a variable.

The cookie name is: userAddress

and the cookie value is:

STATE=NY&ZIPCODE=11889&CITY=EASTON&adr1=123 Street&source=

Im looking to read the following:

STATE:
ZIPCODE:
CITY:
adr1:

Then assign the value to a variable name.

var cookieState ="";
var  cookieZip ="";
var cookieCity ="";
var cookieAdd="";
0
Comment
Question by:yando18
  • 4
  • 4
8 Comments
 
LVL 84

Expert Comment

by:Dave Baldwin
ID: 38315232
Use the 'getCookie' function on this page http://www.w3schools.com/js/js_cookies.asp .  Then the 'split' function on this page http://www.w3schools.com/jsref/jsref_split.asp to separate the name/value pairs.  Then use it again to separate the names from the values.
0
 

Author Comment

by:yando18
ID: 38316009
I can get the cookie however cant split it and assign it to variables. How would I do that? w3schools doesn't help me.
0
 

Author Comment

by:yando18
ID: 38317541
Here is some sample code.

       var c = document.cookie.split('; ');
               cookies = {};

               for(var i=c.length-1; i>=0; i--){
                  C = c[i].split('=');
                  cookies[C[0]] = C[1];
               }

       		var addressCookie = cookies['userAddress'];
       		var addressItems = addressCookie.split('&');
       		for(var i=0,l=addressItems.length; i<l; i++){
       			var addressItem = addressItems[i];
       			if(addressItem.indexOf('STATE')) {
       				cookieState = addressItem.split('=')[1];
       			}
       			if(addressItem.indexOf('ZIPCODE')) {
       				ecookieZip = addressItem.split('=')[1];
       			}
       			if(addressItem.indexOf('CITY')) {
       				cookieCity = addressItem.split('=')[1];
       			}
       		}
       

Open in new window

0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 84

Expert Comment

by:Dave Baldwin
ID: 38317692
Try this.  It sets the cookie then retrieves the info.  Remember that cookie data is supposed to be URL encoded.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>JS Cookie test</title>
<script type="text/javascript">
<!--
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}

function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  x=x.replace(/^\s+|\s+$/g,"");
  if (x==c_name)
    {
    return unescape(y);
    }
  }
}
// -->
</script>
</head>
<body onload="setCookie('userAddress','STATE=NY&ZIPCODE=11889&CITY=EASTON&adr1=123%20Street&source=',1);">
<h1>JS Cookie test</h1>
<script type="text/javascript">
<!--
var cookieState ="";
var cookieZip ="";
var cookieCity ="";
var cookieAdd=""; 
var x,uapc;
var ua = getCookie("userAddress");
var uap = ua.split('&');
for (x in uap)
  {
  uapc = uap[x].split('=');
	if(uapc[0] == 'STATE') {
		document.write("STATE = "+uapc[1]+"<br>");
		cookieState = uapc[1];
		}
	if(uapc[0] == 'ZIPCODE') {
		document.write("ZIPCODE = "+uapc[1]+"<br>");
		cookieZip = uapc[1];
		}
	if(uapc[0] == 'CITY') {
		document.write("CITY = "+uapc[1]+"<br>");
		cookieCity = uapc[1];
		}
	if(uapc[0] == 'adr1') {
		document.write("adr1 = "+uapc[1]+"<br>");
		cookieAdd = uapc[1];
		}
  }
document.write(cookieState+" "+cookieZip+" "+cookieCity+" "+cookieAdd+"<br>");	
// -->
</script>
</body>
</html>

Open in new window

0
 

Author Comment

by:yando18
ID: 38317864
Thanks for you response it appears that the cookie is not url encoded which is probably the reason why Im having so much trouble. Any thoughts?
0
 
LVL 84

Expert Comment

by:Dave Baldwin
ID: 38317885
All 'normal' methods of setting cookies URL-encode the data parts.  If you're talking about the code you posted above, it doesn't make any sense to me.  That's why I posted an alternate version.  The code I borrowed from W3Schools 'unescapes' the data when it returns it.
0
 

Author Comment

by:yando18
ID: 38317906
Working with cookies is new to me, so I'm working with the code you sent above and get returned this.

Uncaught TypeError: Object #<Object> has no method 'split'  

on this line:  uapc = uap[x].split('=');
0
 
LVL 84

Accepted Solution

by:
Dave Baldwin earned 2000 total points
ID: 38318069
That was interesting.  Here is a slightly different version that works in all browsers... as long as it comes from a web server and not from a 'file://'.  IE didn't like the 'split' and the 'var' on the same line for "var uap = ua.split('&');" and Chrome and Safari will not set the cookie if the page is loaded as a 'file://' instead of 'http://' from a web server.  In addition, you have to refresh the page once to get it to work.  It appears that the 'setcookie' routine isn't running before or at least enough before the 'getcookie' code.  The cookie shows up on the page refresh.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>JS Cookie test</title>
<script type="text/javascript">
<!--
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}

function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  x=x.replace(/^\s+|\s+$/g,"");
  if (x==c_name)
    {
    return unescape(y);
    }
  }
}
// -->
</script>
</head>
<body onload="setCookie('userAddress','STATE=NY&ZIPCODE=11889&CITY=EASTON&adr1=123%20Street&source=',1);">
<h1>JS Cookie test</h1>
<script type="text/javascript">
<!--
var cookieState ="";
var cookieZip ="";
var cookieCity ="";
var cookieAdd=""; 
var x,ua, uap, uapc;
ua = getCookie("userAddress");
//document.write(ua+"<br>");
uap = ua.split('&');
for (x in uap)
  {
  uapc = uap[x].split('=');
	if(uapc[0] == 'STATE') {
		document.write("STATE = "+uapc[1]+"<br>");
		cookieState = uapc[1];
		}
	if(uapc[0] == 'ZIPCODE') {
		document.write("ZIPCODE = "+uapc[1]+"<br>");
		cookieZip = uapc[1];
		}
	if(uapc[0] == 'CITY') {
		document.write("CITY = "+uapc[1]+"<br>");
		cookieCity = uapc[1];
		}
	if(uapc[0] == 'adr1') {
		document.write("adr1 = "+uapc[1]+"<br>");
		cookieAdd = uapc[1];
		}
  }
document.write(cookieState+" "+cookieZip+" "+cookieCity+" "+cookieAdd+"<br>");
// -->
</script>
</body>
</html>

Open in new window

0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article discusses four methods for overlaying images in a container on a web page
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
The viewer will the learn the benefit of plain text editors and code an HTML5 based template for use in further tutorials.
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.
Suggested Courses

564 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question