Try this quick little demo, as it shows you how easy it is store information with cookies in JavaScript. We have seen how to use cookies and session variables in PHP. There are a few big differences though between cookies and sessions,
Cookies are used to store information on the browser. This is data that the webserver wants to know about, but will not store internally. There are quite a few use cases for this. We could store information that records who you are, such as an authentication token. It is also useful for pages that use shopping carts, and in a very common use case to track you across websites (3rd party) to support ads.
In JavaScript, cookies are defined within a string, such that:
document.cookie = "username=Joe";
document.cookie = "username=John";
document.cookie = "role=member";
The result of this "assignment" will be that document.cookie has the content:
username=John; role=member
document.cookie = "username=Joe; expires=Tue, 24 Nov 2020 15:20:00 UTC";
document.cookie = "username=Joe; expires=Tue, 26 Nov 2019 15:20:00 UTC; path=/~mXXXXXX/IT350";
document.cookie = "username=Joe; expires=Wed, 01 Jan 1970 00:00:00 UTC; path=/~mXXXXXX/IT350";
To make our life a bit easier, we can use a function similar with the one from w3schools. Don't forget to "escape" the values, which will replace any special character (such as ; or space) with their equivalent URL encoded code.
// Create cookie with name specified by 'identifier' with value 'value'
// If 'days' is set, sets to expire 'days' days from now.
function createCookie(identifier,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else
var expires = "";
document.cookie = identifier+"="+escape(value)+expires;
} }
Cookies can be accessed in JavaScript via the document.cookie property, which will return all cookies for the page in a string like
cookie1=value1; cookie2=value2; cookie3=value3
In order to access cookies in JavaScript we need to break apart the document.cookie string.
We can use the following function:
// Return the 'value' of the cookie variable with name 'desiredId'
// returns null if no match found.
function readCookie(desiredId) {
var cookies = document.cookie;
// First split the pairs apart on '; '
var pairs = cookies.split("; ");
// Now split each pair on '='. Check if have a match
for (var i=0; i < pairs.length; i++) {
var aPair = pairs[i];
var cookieTokens = aPair.split("=");
var id = cookieTokens[0];
var value = cookieTokens[1];
if (id == desiredId) {
// found desired variable -- return value
return unescape(value);
}
}
return null; // no match;
}
To delete a cookie we need to set it to expire in the past, since we already have a createCookie function, we can use that again just with a date in the past:
function eraseCookie(cname) {
createCookie(cname, "", -1);
}
Remember, all relevant cookies are sent by the browser to the server.