Written by Creationz
|
< Previous
|
Next >
|
|---|
When you develop web pages, especially dynamic ones, you need a tool to personalize the web pages for visitors. A cookie is a piece of data that is stored on the user’s computer to maintain information about the client during and between browser sessions. A web site may store a cookie on the client’s computer to record user preferences or other information that the website can retrieve during the client’s subsequent visits.
For example, a Website can retrieve the user’s name from a cookie and use it to display a personalized greeting.
A browser stores a cookie as a small text files on the client’s hard drive. When you visit the website, the browser locates any cookies written by scripts on that site and makes them available to any scripts located on the site. There are name cookies, password cookies, date cookies etc.
One remarkable feature of the cookies and which differentiates them from ordinary strings is the expiration date after which the browser deletes it.
The document object’s cookie property is used to access a cookie in JavaScript. JavaScript treats a cookie as a string of text.
Syntax:
“identifier=value”
Here, ‘identifier’ is any valid JavaScript variable identifier and value is the ‘value’ of the cookie variable.
Now that you have understood the definition and use of cookies, let us create JavaScript code to create and store cookies on the client’s machine. In the script, we will use a cookie to store the user’s name and display a personalized greeting. When the user visits the webpage for the first time, it asks the user to enter a name and it remembers it through cookies in the subsequent visits.
<html>
<head>
<title> Using Cookies </title>
<script type=”text/javascript”>
<!--
Var now=new Date();
Var hour =now.getHours();
Var name;
If(hour<12)
Document.write(“<h1>Good Morning,”);
Else
{
hour= hour – 12;
if (hour<6)
document.write(“<h1>Good Noon!, “);
else
document.write(“<h1>Good eve,”);
}
If (document.cookie)
{
//convert the escape characters in the cookie string to their English notation
Var myCookie=unescape(document.cookie);
}
Else
{
Name=window.prompt(“please enter your name”,”Reha”);
Document.cookie=escape(name); // convert hexadecimal escape sequences //back to English characters for display in a web page.
}
Document.writeln( name+ “<a href=\” JavaScript:wrongperson() \”>” + click here if you are not “ + name + “</a>”);
//reset if wrong person
{
Document.cookie=”null;” + “expires=01-Jan-2011 00:00:01 GMT”;
Location.reload();// reload to get a new name
}
// -->
</script>
</head>
<body> Click Refresh to run the script again </body>
</html>
</head>
This ends our tutorial on cookies, their creation and storing procedure.
|
< Previous
|
Next >
|
|---|