JavaScript Cookies


A cookie is an amount of information that persists between a server-side and a client-
side. A web browser stores this information at the time of Browsing

A cookie contains the information as a string generally in the form of a name value pair
separated by semi-colons. It maintains the state of a user and remembers the user's
Information among all the web pages

How Cookies Works?


When a user sends a request to the server, then each of that request is treated
as a new request sent by the different user.
So, to recognize the old user, we need to add the cookie with the response from
the server
browser at the client-side.
Now, whenever a user sends a request to the server, the cookie is added with
that request automatically. Due to the cookie, the server recognizes the users.

How to create a Cookie in JavaScript?


In JavaScript. we can create, read, update and delete a cookie by
using document.cookie property

The following syntax is used to create cookie:

document.cookie="name=value";

Javascript cookie example


Let's see an example to set and get a cookie.


<html>
<head>
</head>
<body>
<input type="button"value="setCookie" onclick="setCookie()">
 <input type="button" value="getCookie" onclick="getCookie()">
<script>
function setCookie()
{
document.cookie="username=Duke Martin"
}
function getCookie()
{
if(document.cookie.length!=0)
{

alert(document.cookie);
}
else
{
alert("Cookie not available");

}
}
</script>

</body>

</html>

Comments

Popular posts from this blog

Node.js Cheat Sheet

Codeigniter ! Simple But Powerful

Enhancing Supply Chain Security and Cloud-Native Development with Chainguard