Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

my cookie code generates an error

Status
Not open for further replies.

Ito2233

MIS
Sep 2, 2003
77
0
0
US
I have a simple webpage to test the functionality of a cookie. THe user chooses an animal from the menu, and if the checkbox is selected, the cookie is written and the document loads another page. After the cookie is set, a ReadCookie function is called to redirect the user.
When I click on GO, I get a "Page cannot be displayed" error. What am I doing wrong?

Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
  <title>Cookie Test</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  
<SCRIPT LANGUAGE="JavaScript">
<!-- Begin
function SetCookie() {  
var box = document.form1.region.options;
var chosen_value = box[box.selectedIndex].value;

if (document.form1.remember.checked == true){
    var expiration = new Date("December 1, 2004");
    expiration = expiration.toGMTString();
	document.cookie = "name=" + chosen_value + ";expires=" + expiration;
    alert(document.cookie);
}
Redirect(chosen_value); 

}

function Redirect(choice) {
var url = 'none.html';
if (choice != null) {
    switch (choice) {
	        case 'americas' : url = 'cat.html'; 
	     	break;
            case 'canada' : url = 'dog.html'; 
	     	break;
            case 'other' : url = 'eel.html';
		    break;
    }
    document.location = url;
	
}
else {
      alert("Please select a region and click \"Go\".");
 }
}

function ReadCookie() {
if (document.cookie != "") {
    var url = 'error.html';
	cookie_data = document.cookie;
    switch (cookie_data) {
	        case 'americas' : url = 'cat.html'; 
	     	break;
            case 'canada' : url = 'dog.html'; 
	     	break;
            case 'other' : url = 'eel.html';
		    break;
    }
    document.location = url;
}
else {return}
}
//  End -->
</script>
</head>
<body topmargin="0" leftmargin="0" marginheight="0" marginwidth="0" onLoad="ReadCookie()">
		<form method="post" name="form1">
        <select name="region">
				<option value="americas">USA/Latin America</option>
				<option value="canada">Canada</option>
				<option value="other">Other Regions</option>
		</select> 
        <input type="submit" name="Submit" value="Go" onClick="setCookie()"> 
        <input type="checkbox" name="remember" value="yes">
                    Remember my selection</td>	
					
						</form>
				
</body>
</html>
 
This:

Code:
var box = document.form1.region.options;
var chosen_value = box[box.selectedIndex].value;

Should be this:

Code:
var box = document.form1.region;
var chosen_value = box.options[box.selectedIndex].value;

*cLFlaVA
----------------------------
Breaking the habit...
 
That solves part of the problem. However, the cookie setting-page never loads, because I am being redirected as soon as the page loads. There is a flaw in my code logic, and I think it is because I am not properly detecting the absence of a cookie. In my original code (posted above), I have:
Code:
if (document.cookie != "") {
    statements...   
}
This condition is evaluating to true, even though no cookie has been set. I thought the empty string the equivalent of no cookie. Apparently, I was wrong. What would be the correct way of doing it?
Thanks
 
Try

Code:
if (document.cookie.length > 0) {
   statements...
}

*cLFlaVA
----------------------------
Lois: "Peter, you're drunk!"
Peter: "I'm not drunk, I'm just exhausted from stayin' up all night drinking!
 
Code:
<SCRIPT LANGUAGE="JavaScript">
<!-- Begin
function SetCookie() {  
var box = document.form1.region.options;
var chosen_value = box[box.selectedIndex].value;

if (document.form1.remember.checked == true){
    var expiration = new Date("December 1, 2004");
    expiration = expiration.toGMTString();
    document.cookie = "name=" + chosen_value + "&expires=" + expiration;
}
Redirect(chosen_value); 

}

function Redirect(choice) {
var url = 'none.html';
if (choice != null) {
    switch (choice) {
            case 'americas' : url = 'cat.html'; 
             break;
            case 'canada' : url = 'dog.html'; 
             break;
            case 'other' : url = 'eel.html';
            break;
    }
    document.location = url;
    
}
else {
      alert("Please select a region and click \"Go\".");
 }
}

function readCookie(varname) 
{
  var value = '';
  cookie_data = document.cookie;
  cookievals = cookie_data.split("&");
  var segment;
  for (i=0;i<cookievals.length;i++)
  {
    segment = cookievals[i].split("=");
    if (segment[0] == varname)
    {
      value = segment[1];
      break;
    }
  }
  return value;
}
function doLoad()
{
  var name = readCookie("name");
  if (url != "")
  {
    Redirect(url);
  }
}

--Chessbot

"So it goes."
Kurt Vonnegut, Slaughterhouse Five
 
Wow, I'm baffled. cLFlava, I made the change you suggested and it fixed that part of the code. The problem is that the cookie is still not being written. In fact, I added an alert box in the third line of the SetCookie function just to see whether that function was being run at all:
Code:
function SetCookie() {  
var box = document.form1.region;
var chosen_value = box.options[box.selectedIndex].value;
alert("Why isn't it working?");
statements....
}

This function is the first thing that is supposed to run when the user clicks on GO. But, alas, I am getting no alert boxes, let alone cookies...Why isn't my simple script running?

Chessbot, I'll try your solution next...
 
2 things:
1. Your capitalization is wrong. The function is SetCookie and you are calling setCookie

2. Not sure if it makes a difference, but change the type="submit" to type="button"

--Chessbot

"So it goes."
Kurt Vonnegut, Slaughterhouse Five
 


Silly Question
What type of field is the "region" field?

Could you post your complete code so I can debug?

*cLFlaVA
----------------------------
Lois: "Peter, you're drunk!"
Peter: "I'm not drunk, I'm just exhausted from stayin' up all night drinking!
 
cLFlaVA:
The page is in the first post, I believe.

--Chessbot

"So it goes."
Kurt Vonnegut, Slaughterhouse Five
 
Okay, I feel I'm on the final lap.
Chessbot, the capitalization suggestion solved the biggest problem, ie the function not running.

I've made a few modifications to the code, based on all of your suggestions. I have added some alerts to also debug better. There is one last problem I'm facing, and I know where it's occurring, just not how to solve it.

When the Redirect function is called, the correct HTML address is assigned to the variable URL (which is in turn assigned to document.location). When I check the contents of document.location, it shows "index.html", the starting file. Redirection fails.

Curiosuly, while the same thing happens in the ReadCookie function (document.location displaying "index.html" after being assigned a URL), redirection works!!

Any ideas? Here is the full, updated code:

Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
  <title>Cookie Test</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  <SCRIPT LANGUAGE="JavaScript">
  <!-- Begin

function SetCookie() {  
var box = document.form1.region;
var chosen_value = box.options[box.selectedIndex].value;

if (document.form1.remember.checked == true){
    var expiration = new Date("December 1, 2004");
    expiration = expiration.toGMTString();
	document.cookie = "name=" + chosen_value + ";expires=" + expiration;
}
Redirect(chosen_value); 
}

function Redirect(choice) {
alert(choice);
var url;
if (choice != null) {
    switch (choice) {
	        case "americas" : url = "[URL unfurl="true"]http://192.168.201.133/cat.html";[/URL] 
	     	break;
            case "canada" : url = "[URL unfurl="true"]http://192.168.201.133/dog.html";[/URL] 
	     	break;
            case "other" : url = "[URL unfurl="true"]http://192.168.201.133/eel.html";[/URL]
		    break;
    }
	var temp = "This is the url: " + url;
	alert(temp);
        document.location = url;
	alert(document.location);
}
else {
      alert("Please select a region and click \"Go\".");
 }
}

function ReadCookie() {
if (document.cookie.length > 0)  {
    var url;
    cookie_data = document.cookie;
    alert(cookie_data);
    cookie_pieces = cookie_data.split("=");
    alert(cookie_pieces[1]);
    
    switch (cookie_pieces[1]) {
	        case "americas" : url = "[URL unfurl="true"]http://192.168.201.133/cat.html";[/URL] 
	     	break;
            case "canada" : url = "[URL unfurl="true"]http://192.168.201.133/dog.html";[/URL] 
	     	break;
            case "other" : url = "[URL unfurl="true"]http://192.168.201.133/eel.html";[/URL]
		    break;
    }
    alert(url);
    document.location = url;
    alert(document.location);
}
else {return}
}
//  End -->
</script>
</head>
<body topmargin="0" leftmargin="0" marginheight="0" marginwidth="0" onLoad="ReadCookie()">
        <form method="post" name="form1">
        <select name="region">
                <option value="americas">USA</option>
                <option value="canada">Canada</option>
                <option value="other">Other Regions</option>
        </select> 
        <input type="submit" name="Submit" value="Go" onClick="SetCookie()"> 
        <input type="checkbox" name="remember" value="yes">
                    Remember my selection</td>    
                    
        </form>
</body>
</html>
 
I don't know what the difference is, but try using [tt]window.location.replace(url)[/tt] instead of [tt]document.location = url[/tt].

--Chessbot

"So it goes."
Kurt Vonnegut, Slaughterhouse Five
 
I did as you suggested, and the results, ironically enough, are exactly the same. Ie, redirection fails when you click on GO and the cookie is set, but it works when you open up the page once the cookie has been created. Strange!!!!!
 
Might it have something to do with IIS??? The following is the message I get when the first redirection is attempted:

The page cannot be displayed
The page you are looking for cannot be displayed because the page address is incorrect.
_____________________________

HTTP 405 - Resource not allowed
Internet Information Services
 
I've noticed something strange...to make sure that my javascript wasn't failing because of my html references or some file browsing issue, I decided to use the addresses of famous search engines as the values to assign to the variable URL. What's strange is that the cookie file stored on my computer changes name based on what value is assigned to the variable. Ie, I get username@yahoo.com, or username@google.com, or username@lycos.com. Shouldn't the name of the cookie include the domain of the server setting the cookie (ie, MY server)???
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top