Nairaland Forum

Welcome, Guest: Join Nairaland / Login / Trending / Recent / New
Stats: 1258559 members, 1698195 topics. Date: Thursday, 23 October 2014 at 02:42 AM

How To Store Data With javascript / Javascript Cookie Workshop - Webmasters - Nairaland

Nairaland Forum / Science/Technology / Webmasters / How To Store Data With javascript / Javascript Cookie Workshop (15917 Views)

Hlp With Javascript Snippet To Validate A User's Cell Phone Number Input / [SOLVED!] Cookie Not Set Using Setcookie(). Help! / Trouble With Javascript Code (1) (2) (3) (4)

(0) (Reply) (Go Down)

How To Store Data With javascript / Javascript Cookie Workshop by dhtml18(m): 2:29pm On Jan 06, 2009
Today, we are going to learn how to save website information into the client system. This is the trick also to remembering the last page a user visited on your website after the client closes the browser, some use it to support sessions by saving username, i am talking of that feature we keep seeing on login pages that says - remember me on this computer, all these and lots ore can be done with cookies.

Since this is a workshop, i will talk about using cookies directly and how to use classes to access cookies.

Before we go into coding let me paste a few intros here


What are cookies? A "cookie" is a small piece of information sent by a web server to store on a web browser so it can later be read back from that browser. This is useful for having the browser remember some specific information.

What are they used for ? An example is when a browser stores your passwords and user ID's. They are also used to store preferences of start pages, both Microsoft and Netscape use cookies to create personal start pages. Common cookies which companies use are find info are listed below:

Online Ordering Systems. An online ordering system could be developed using cookies that would remember what a person wants to buy, this way if a person spends three hours ordering CDs at your site and suddenly has to get off the net they could quit the browser and return weeks or even years later and still have those items in their shopping basket.

Site Personalization. This is one of the most beneficial uses, let's say a person comes to the MSNBC site but doesn't want to see any sports news. They allow people to select this as an option, from then on (until the cookie expires) they wouldn't see sports news. This is also usefull for start pages.

Website Tracking. Here is a hot button! A lot of people think it is an invasion of privacy, if a web site designer wanted to see what interests them. Site tracking can show you "Dead End Paths", places in your website that people go to and then wander off because they don't have any more interesting links to hit. It can also give you more accurate counts of how many people have been to pages on your site. You could differentiate 50 unique people seeing your site from one person hitting the reload button 50 times.

Targeted Marketing. This is probably one of the main uses of cookies, they can be used to build up a profile of where you go what adverts you click on, this information is then used to target adverts at you, which they think are of interest, companies also use cookies to store which adverts have been displayed so the same advert does not get displayed twice. Doubleclick's use of cookies.

User ID's. In Internet Explorer the first part of the cookie is your windows log in name, It's not certain if this is passed on to the server.

How Do They Work A command line in the HTML of a document tell the browser to set a cookie of a certain name or value. Here is an example of some script used to set a cookie. Set-Cookie: NAME=VALUE; expir es=DATE; path=PATH; domain=DOMAIN_NAME; secure Cookies are usually run from CGI scripts, but they can also be set or read by Javascript.

Security? An HTTP Cookie cannot be used to get data from your hard drive, get your email address or steal sensitive information about your person. Early implementations of Java and JavaScript could allow people to do this but for the most part these security leaks have been plugged. But HTTP Cookie can be used to track where you travel over a particular site, This site tracking can be easily done without using cookies as well, using cookies just makes the tracking data a little more consistent. If you want to disallow cookies you can do so with version 3.0 or greater of Netscape. Go to the Options Menu Select the Network Preferences Menu Item From the window that appears Select Protocols Locate the Section Show an Alert Before Check the box labeled Accepting a Cookie From now on you will get an Alert box telling you that a server is trying to set a cookie at your browser. It will tell you what the cookie value is and how long it will last before it is deleted
Re: How To Store Data With javascript / Javascript Cookie Workshop by dhtml18(m): 3:03pm On Jan 06, 2009
Demo 1: http://.net/demos/cookies/change.htm - storing personal info
Demo 2: http://.net/demos/cookies/jc2.htm - javascript counter

You can download those demos on http://.net/?net=dl

I will not explain those source codes - those are complete samples - but rather i want to give a short training on the basics of cookies.

At this point i am tempted to create a cookie class for easy learning, then i will now break down the class

cookie.class.js

function jcookies() {}
jcookies.prototype.online=function() {return location.href.indexOf("http"wink==-1 ? false : true;}
jcookies.prototype.set=function (cname,cvalue) {
  if(this.online()) {document.cookie = cname + "=" + escape(cvalue) + "; expires=Mon, 31 Dec 2099 23:59:59 UTC;path=/;";}
  else {document.cookie = cname + "=" + escape(cvalue) + "; expires=Mon, 31 Dec 2099 23:59:59 UTC;";}
}
jcookies.prototype.erase=function(cname) {
  if(this.online()) {document.cookie = cname + "=" + "" + "; expires=Mon, 31 Dec 1899 23:59:59 UTC;path=/;";}
  else {document.cookie = cname + "=" + "" + "; expires=Mon, 31 Dec 1899 23:59:59 UTC;";}
}
jcookies.prototype.get=function(sName) { var aCookie = document.cookie.split("; "wink;
  for (var i=0; i < aCookie.length; i++)   {
    var aCrumb = aCookie[i].split("="wink;
    if (sName == aCrumb[0])
      return unescape(aCrumb[1]);
  }
  return "";
}



The class contains 3 methods/functions:
set - to create a cookie
get - to retrieve a cookie
erase- to clear out a cookie

I am going to implement that class now

cookie.test.html

<title>My Cookie Test</title>
<script src="cookie.class.js"></script>
<script>
var food=new jcookies();

function savex() {
food.set("meal",cook.value);
alert("Swallowed "+cook.value);
}

function loadx() {
cook.value=food.get("meal"wink;
}

function erasex() {
cook.value="";
food.erase("meal"wink;
alert("Vomited meal"wink;
}

</script>


<input type="text" id="cook">
<input type="button" value="Save" onclick="savex()">
<input type="button" value="Load" onclick="loadx()">
<input type="button" value="Vomit" onclick="erasex()">


I will leave it for you to compile the 2 - demo will be http://.net/demos/cookies/cookie.test.html

And for this demo, all you need do is launch it, type in a value, click on save.
You can close the browser, then reopen the page in the same browser on the same system, then click on the load button, u should have your contents back.

Next lesson: we are going to break the code code into bits and pieces.
Re: How To Store Data With javascript / Javascript Cookie Workshop by dhtml18(m): 3:06pm On Jan 06, 2009
Demo 1: http://.net/demos/cookies/change.htm - storing personal info
Demo 2: http://.net/demos/cookies/jc2.htm - javascript counter

You can download those demos on http://.net/?net=dl

I will not explain those source codes - those are complete samples - but rather i want to give a short training on the basics of cookies.

At this point i am tempted to create a cookie class for easy learning, then i will now break down the class

cookie.class.js

function jcookies() {}
jcookies.prototype.online=function() {return location.href.indexOf("http"wink==-1 ? false : true;}
jcookies.prototype.set=function (cname,cvalue) {
 if(this.online()) {document.cookie = cname + "=" + escape(cvalue) + "; expires=Mon, 31 Dec 2099 23:59:59 UTC;path=/;";}
 else {document.cookie = cname + "=" + escape(cvalue) + "; expires=Mon, 31 Dec 2099 23:59:59 UTC;";}
}
jcookies.prototype.erase=function(cname) {
 if(this.online()) {document.cookie = cname + "=" + "" + "; expires=Mon, 31 Dec 1899 23:59:59 UTC;path=/;";}
 else {document.cookie = cname + "=" + "" + "; expires=Mon, 31 Dec 1899 23:59:59 UTC;";}
}
jcookies.prototype.get=function(sName) { var aCookie = document.cookie.split("; "wink;
 for (var i=0; i < aCookie.length; i++)   {
   var aCrumb = aCookie[i].split("="wink;
   if (sName == aCrumb[0])
     return unescape(aCrumb[1]);
 }
 return "";
}



The class contains 3 methods/functions:
set - to create a cookie
get - to retrieve a cookie
erase- to clear out a cookie

I am going to implement that class now

cookie.test.html

<title>My Cookie Test</title>
<script src="cookie.class.js"></script>
<script>
var food=new jcookies();

function savex() {
food.set("meal",cook.value);
alert("Swallowed "+cook.value);
}

function loadx() {
cook.value=food.get("meal"wink;
}

function erasex() {
cook.value="";
food.erase("meal"wink;
alert("Vomited meal"wink;
}

</script>


<input type="text" id="cook">
<input type="button" value="Save" onclick="savex()">
<input type="button" value="Load" onclick="loadx()">
<input type="button" value="Vomit" onclick="erasex()">


I will leave it for you to compile the 2 - demo will be http://.net/demos/cookies/cookie.test.html

And for this demo, all you need do is launch it, type in a value, click on save.
You can close the browser, then reopen the page in the same browser on the same system, then click on the load button, u should have your contents back.

Next lesson: we are going to break the code code into bits and pieces.
Re: How To Store Data With javascript / Javascript Cookie Workshop by dhtml18(m): 3:19pm On Jan 06, 2009
This is How to Create a Cookie
document.cookie = cname + "=" + escape(cvalue) + "; expires=Mon, 31 Dec 2099 23:59:59 UTC;path=/;";
where cname is the name of the cookie and cvalue is the information the cookie contains. The date specified there
is the expiry date of the cookie when the browser will automatically delete the cookie.
The path refers to what domain within your site can access it. For learners, just use / if you are online,
but if you are running this without a web server as c:\documents and settings\desktop\cookie.test.html just use / instead.


This is How To Get A Cookie

function getCookie(sName) {
for (var i=0; i < aCookie.length; i++) {
var aCrumb = aCookie[i].split("="wink;
if (sName == aCrumb[0])
return unescape(aCrumb[1]);
}
return ""; //not found
}


All the cookies of a web page are attached to the document that created them - so you need to run a loop through them.
Getting cookies is easier than creating them - just understand how the structure works in case you cannot read
jscript arrays.



*************************** That Ends This Workshop ***********************************************8

Questions can now follow as usual if any.

(0) (Reply)

Your Top 5 Nigerian Everyday Websites / All these Nigerian Online E-Commerce Shops / Your Favorite Nigerian Website(s)?

(Go Up)

Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health
religion celebs tv-movies music-radio literature webmasters programming techmarket

Links: (0) (1) (2) (3) (4) (5) (6) (7) (8) (9)

Nairaland - Copyright © 2005 - 2014 Oluwaseun Osewa. All rights reserved. See Nairalist and How To Advertise. 111
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.