June 22, 2009

0 Javascript Cookies

Javascript Cookies

A cookie is often used to identify a user.

What is a cookie?

A cookie is a variable that is stored on the visitor' s computer. Each time the same computer requests a page with a browser, It will send the cookie too. With JavaScript, you can both create and retrieve cookie values.

Examples of cookies:

1) Name cookie - The first time a visitor arrives to your web page, he or she must fill in the her/his name. The name is then stored in a cookie. Next time the visitor arrives at your page, he or she could get a welcome message like "Welcome Jon abc" The name is retrieved from the stored cookie.

2 ) password Cookie - The first time a visitor arrives to your web page, he or she must fill in a password. The password is then stored in a cookie. Next time the visitor arrives at your page, the password is retrieved from the cookie.

3 ) Date cookie - The first time a visitor arrives to your web page, the current date is stored in a cookie. Next time the visitor arrives at your page, he or she could get a message like "Your last visit was on Tuesday August 11, 2005!" the date is retrieved from the stored cookie


Date and Store a Cookie

In this example we will create a cookie that stores the name of a visitor. The first time a visitor arrives to the web page, he or she will be asked to fill in her/his name. The name is then stored in a cookie. The next time the visitor arrives at the same page, he or she will get welcome message.

First, we create a funcion that stores the name of the visitor in a cookie variable:

function setCookie (c_name,value,expiredays)
{
var exdate=new Date( )
exdate.setData (expiredays)
document.cookie=c_name+ "=" +escape(value) +
((expiredays==null) ? "" ; ";expires="+exdate)
}

0 comments:

Post a Comment

Blogger Themes

 
Powered by Blogger