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>
2
  • Have you used Firebug to check whether your JavaScript is even setting the cookie? Commented Apr 5, 2012 at 15:21
  • Hi, I don't know how can I check in firebug cookie. I will check now thx. Commented Apr 5, 2012 at 15:37

2 Answers 2

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);">
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Thanks alot. it is not working I will try somthing else thx again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.