Need to read a cookie value

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="";
yando18Asked:
Who is Participating?
 
Dave BaldwinFixer of ProblemsCommented:
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
 
Dave BaldwinFixer of ProblemsCommented:
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
 
yando18Author Commented:
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
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

 
yando18Author Commented:
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
 
Dave BaldwinFixer of ProblemsCommented:
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
 
yando18Author Commented:
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
 
Dave BaldwinFixer of ProblemsCommented:
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
 
yando18Author Commented:
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.