www.pickatutorial.com Computer Tutorials
Top eBooks: C/C++ | C# | Android | Mathematics | Database | Cloud | Graphics | Networking | Oracle | Hardware | AI
Top Tutorials: C/C++ | C#.NET | PHP MySQL | Java | Java Script | jQuery | HTML | xHTML | HTML5 | VB Script| CSS
Lessons JavaScript Working with Cookies Bookmark and Share
Tutorial Home
Lesson 1
Lesson 2
Lesson 3
Lesson 4
Lesson 5
Lesson 6
Lesson 7
Lesson 8
Lesson 9
Lesson 10
Lesson 11
Lesson 12
Lesson 13
Lesson 14
Lesson 15
Lesson 16
Lesson 17
Lesson 18
Lesson 19
Lesson 20
Lesson 21
Lesson 22
Lesson 23
Lesson 24
Lesson 25
Lesson 26
Lesson 27
Lesson 28
Lesson 29
Lesson 30
Lesson 31
Lesson 32
Lesson 33
Lesson 34
Lesson 35
Lesson 36
Lesson 37
Lesson 38
Lesson 39
Lesson 40
Lesson 41
Lesson 42
Lesson 43
Lesson 44
Lesson 45
Lesson 46
Lesson 47
Lesson 48
Lesson 49
A Cookie in JavaScript is a small chunk of data stored by the web browser on the user's computer. Cookies allow websites to store a small piece of information on the visitor's computer, that can later be retrieved, only by the same website that stored it.

We can store a user's name, date and time of user's last visit, user's id / password etc. ina cookie.

There are two main operations that we do with a cookie. The first is to set the cookie and the second is to retrieve the cookie, where setting a cookie means to store information and to retrieve a cookie means to retrieve information, stored earlier in a cookie.

A cookie is stored on a user's computer in the form of a small text file, containing:

  1. A name-value pair containing the actual data
  2. An expiry date after which it is no longer valid
  3. The domain and path of the server it should be sent to

Cookies can be created, read and erased by JavaScript. We access them through the document.cookie property.

The following line of code asks the visitor's name and stores the same in a cookie:

document.cookie="name=" + prompt("What is your name?");

The following function retrieves the above cookie and alerts the name of the visitor:

function getCookieValue(key)
{
currentcookie = document.cookie;
if (currentcookie.length > 0)
{
first = currentcookie.indexOf(key + "=");
if (first != -1)
{
first = first + key.length + 1;
last = currentcookie.indexOf(";",first);
if (last == -1)
{
last = currentcookie.length;
}
return unescape(currentcookie.substring(first, last));
}
}
return "";
}

alert(getCookieValue("name"));


Next >>> Lesson No. 45: JavaScript Form Validation





Home - Advertise - Contact - Disclaimer - About Us
© Since 2006 pickatutorial.com -- All Rights Reserved.