Web Hosting Talk







View Full Version : Javascript Cookie question


Mekhu
12-02-2002, 03:04 PM
Hey guys... basically I want it so a user enter there name, strikes enter and a welcome message is displayed... not happening for me though...

------------------

<html>
<head>
<title></title>

<script language="JavaScript">
expireDate = new Date;
expireDate.setMonth(expireDate.getMonth()+6);
firstName = "";
if (document.cookie != "") {
firstName = document.cookie.split("=")[1];
}
function setCookie() {
firstName = document.myForm.nameField.value;
document.cookie = "firstName="+firstName+";expires=" +
expireDate.toGMTString();
}
</script>

</head>
<body>

<form name="myForm">
Name:
<input type="text" name="nameField" onBlur="setCookie()">
</form>

<script language="JavaScript">
if (document.cookie != "") {
document.write("<br>Welcome to my site, " + firstName);
}
</script>


</body>
</html>

Rich2k
12-03-2002, 05:33 AM
You can't read a cookie on the same page as you set the cookie i.e. you have to at least refresh or change the page as the cookie is sent in the header and when you set the cookie the header has already been sent to the browser so you need to go to a new page.

sylow
12-03-2002, 08:29 AM
<html>
<head>
<title></title>

<script language="JavaScript">
expireDate = new Date;
expireDate.setMonth(expireDate.getMonth()+6);
firstName = "";
if (document.cookie != "") {
firstName = document.cookie.split("=")[1];
}

function setCookie() {
firstName = document.myForm.nameField.value;
document.cookie = "firstName="+firstName+";expires=" +
expireDate.toGMTString();
}
</script>

</head>
<body>

<form name="myForm">
Name:
<input type="text" name="nameField" onBlur="setCookie()">
</form>
<a href="javascript:alert(document.cookie)">hello world</a>

</script>


</body>
</html>
-----------------------
This works for me very well, your problem is you are trying to write something when there is no chance to write