View Full Version : How do I add a unique number to each cookie?

04-27-2007, 08:07 PM
I'm trying to set a persistent cookie with a unique value when people visit my site through a certain landing page. I currently use

num_days = 180;
function ged(noDays){
var today = new Date();
var expr = new Date(today.getTime() + noDays*24*60*60*1000);
return expr.toGMTString();

function setCookie(){

document.cookie = "google=yes; path=/; expires=" + ged(num_days);



I'd like each cookie to have a unique number added to it for tracking purposes...anyone who knows?

04-27-2007, 08:42 PM
The timestamp mostly unique, unless you have substantial traffic, where it is possible for two people to arrive at the same time. If you require a pure JavaScript solution, then append a random number to the date.

var randomnumber=Math.floor(Math.random()*n)

Where n is the maximum number you want plus one, so if I want values 0-100, then n would be 101.

However, best practices would not have you create this identifier in JavaScript. It would be better to make a database on server called cookies (or something like that) with auto incrementation enabled on the primary key (PK). Then with an AJAX call, or simple server-side scripting, ask the database for the next available PK. This approach also allows you to use this Id to track the user's activity around your site and subsequent visits.

04-30-2007, 07:53 PM
Thanks for the help, I'm still having a little bit of problem actually implementing it. Basically I want to add a random number to this

function setOptinCookie(cookieName){
var start = document.cookie.indexOf(cookieName);
if (start == -1){
document.cookie = "optin=yes; path=/; expires=" + ged(num_days);
} else {



I tried doing this:

function setCookie(){
var randomnumber=Math.floor(Math.random()*1000000000000)
document.cookie = "googleCheck=" + randomnumber ; "expires=" + ged(num_days);



and it gives the cookie a random value, but the "expires=" part doesn't execute properly, so all I get is a session cookie, and I can't get the path to work.

In the top code, how would I add the random number to the cookie without messing out the expiration of the cookie or the path it's set to?


04-30-2007, 10:43 PM
Not sure what you are doing with 'ged(num_days)', but this may help:
var theDate = new Date();
theDate.setDate(theDate.getDate()+5) // 5 day ahead
var num_days = theDate.toUTCString();

function setOptinCookie(cookieName){
var start = document.cookie.indexOf(cookieName);
if (start == -1){
var randomnumber=Math.floor(Math.random()*1000000000000);
document.cookie = "optin=yes" + randomnumber + "; path=/; expires=" + num_days;
else {


05-01-2007, 09:02 PM
Thanks, that did it :thumbsup: