How to send a parameter by cookie using js

Go To StackoverFlow.com

1

I have two HTML files. One file needs to send a title to the second file. The second file needs to receive the title and alert() it. What do I need to change for the code to run as needed?

cookieTitleSend.html

<html>
<head>
<script type="text/javascript">

function setCookie(Title_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var Title_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=Title_name + "=" + Title_value;
}
</script>
</head>
<body onload="setCookie("Title_name",PHP Hello World,1);">
</body>
</html>

cookieTitleReceive.html

<html>
<head>
<script type="text/javascript">
function getCookie(Title_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==Title_name)
    {
    return unescape(y);
    }
  }
}

function checkCookie()
{
var Title_name=getCookie("Title_name");
if (Title_name!=null && Title_name!="")
  {
  alert("Welcome again your Title is
:  " + Title_name);
  }
else 
  {
  Title_name=prompt("There is no title :","");

  }
}
</script>
</head>
<body onload="checkCookie()">
</body>
</html>
2012-04-05 15:08
by israel love php
Have you used Firebug to check whether your JavaScript is even setting the cookie - hohner 2012-04-05 15:21
Hi, I don't know how can I check in firebug cookie. I will check now thx - israel love php 2012-04-05 15:37


2

Your code looks like it has a few problems but you can start with properly wiring up the event handler.

<body onload="setCookie('Title_name','PHP Hello World',1);">
2012-04-05 15:15
by Jeff
I try it is not working - israel love php 2012-04-05 15:18


0

I think there might be some subtle things in your code, check out this link on how to utilize cookies. Namely, that your setter might need to make the following changes:

exdate.setTime(today.getTime() + 3600000*24*exDays);
document.cookie = cookieName+"="+escape(value)
             + ";expires="+exdate.toGMTString();

Something I saw in your loop in GetCookie:

for (i=0;i<ARRcookies.length;i++)

which I think should be:

for (i=0;i<ARRcookies.length-1;i++)

Hope that helps!

-sf

2012-04-05 15:22
by sacredfaith
Thanks alot. it is not working I will try somthing else thx again - israel love php 2012-04-05 15:38
Ads