In the previous tutorials we covered just about everything there is to know about Javascript. If you missed those, the first article in the Javascript Scripting Tutorial can be found here.
In this article we will cover Cookies. Just so you know what to look forward to, we will finish off the whole tutorial by learning how to create an interactive menu and handle errors. Then you’ll be a Javascript expert.
Cookies
With cookies it is possible to store information on a visitors computer so you will recognize them when they return in the future. A cookie is simply a tiny text file (4k) that is stored on a client’s computer. You can only store a total of 20 cookies per computer. You define how long they will stay on that computer, but the visitor can force them to be deleted at any time.
Cookies are most often used to store a code that will allow a website to recognize a returning visitor, or to save transaction information as a purchase is being made. You would want to save transaction data, so that if a visitor is disconnected from your site, mid-purchase, they would be able to jump in were they left off with little confusion.
Creating Some Cookies
You can store a single piece of data on the visitors computer, just like you store single pieces of data in variables. The only difference is that cookies are stored as one big long string. So they have to be incoded and decoded. Also, as mentioned before an expiration date needs to be set at the time of the cookie creation date.
This is a basic way to create a cookie:
document.cookie = nameOfCookie + “=” + valueToStore + expdate + “; path=/”;
You could also set the following attributes:
Reading The Stored Cookie Data
So, you set the cookie and the visitor comes back, how do you read the stored cookie data? If you asked them to enter their user name you could then check if that user name exists with the following if statement.
if (userName == “” || userName == null)
If the answer comes back false, have them register with your website. If it came back true you would retrieve the cookie with the following code:
var searchName = userName + “=”;
var cookies = document.cookie.split(‘;’); // Splits all of the cookies into separate cookies
for (var i=0; i < cookies.length; i++ ) // Cycles through all of the cookies
{
var c = cookies[ i ]; // Assigns the individual array values to variable c
while (c.charAt(0) == ‘ ‘ )
{
c = c.substring(1, c.length); // Extract all of the characters from the string stored in variable c
}
if (c.indexOf(searchName) == 0) // Check if the cookie variable name is stored here
{
var valueStored = c.substring(searchName.length, c.length); // If it is save that value
}
That’s All Folks
That is all there is to know about setting and retrieving cookies with Javascript. If you have any questions leave them in the comment section below.
Till next time…
Excellent article as always, thanks for writing all this informative content on a regular basis.