0

I am trying to send data from one html page to another. I am using cookies to save info that will be retrieve by the another wabpage. However, when the next page wants to get the value of the cookie, it is empty. I think the cookie is being lost when I'm going from one page to another.

Thank You!!!! (Is there better alternative?)

This is how I tried to accomplish this task in JavaScript:

For saving data inside cookies (only for 1 day)

 //HTML page 1
 setCookie("myCookie", myData, 1);

where

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;
}

For getting cookie

//HTML page 2
var cookieValue = getCookie("myCookie");

where

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);
    }
  }
}

1 Answers1

2

While writing your own cookies library is good practice, it can be a little frustrating. I would recommend the use of (and/or reviewing) an existing library such as cookie.js - http://code.google.com/p/cookie-js/source/browse/trunk/cookie.js

As an alternative to cookies, you might find that the HTML5 features localStorage and sessionStorage are helpful, depending on your use case. For more information, see http://diveintohtml5.info/storage.html and/or http://www.html5rocks.com/en/features/offline

psema4
  • 3,007
  • 1
  • 17
  • 22
  • Can I use this library for my e-commerce website? Is it royalty free? Thank you – David Stepanyan Nov 07 '12 at 01:59
  • Can you give me an example of setting and getting data in cookies using cookie.js ? Thank you – David Stepanyan Nov 07 '12 at 02:05
  • 1
    It's under an open source license (a requirement of hosting on Google Code); more specifically it's under the MIT license so using it an e-commerce site should be fine. (Of course, I'm not a lawyer - you should check with one if you're concerned). There's also an example in the project's wiki at http://code.google.com/p/cookie-js/wiki/MainDocumentation – psema4 Nov 07 '12 at 18:30