How to create and read cookies in JavaScript

The cookies are the small bit of the text data that can be stored in the user’s browser so that it can be reuse in the next request. Generally web server instruct to write the cookie on the user’ browser. But you can also manipulate the cookies using JavaScript. You can create, delete, modify and read using the Document.cookie property.

The below example shows how to create and read later the cookie for the user name and age.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>Learn Cookie in JavaScript</title>
  <script type="text/javascript">
      function CreateCookie()
	  {
	    var uname= escape(document.getElementById("txtName").value);
		var uage = escape(document.getElementById("txtAge").value);
		alert("username=" + uname + ";age=" + uage);
	    document.cookie= "username=" + uname + ";age=" + uage;
	  }
	  function ReadCookie()
	  {
	     var allcookies = document.cookie;
         var Arr  = allcookies.split(';');
        for(var i=0; i< Arr.length; i++){
           alert(Arr[i]);
        }
	  }
    </script>
</head>
<body>
    <form id="form1">
        <div>
            Enter your name:<input type="text" id="txtName" />
			Enter your Age:<input type="text" id="txtAge" />
 
			<input type="button" id="btnOk" 
			  value="Create Cookie" onclick="CreateCookie();"/>
			<input type="button" id="btnRead" 
			  value="Read Cookie" onclick="ReadCookie();"/>
        </div>
    </form>
</body>
</html>

From the above you’ll see that the example is creating the cookie in this way:

document.cookie = "key1=value1;key2=value2;

And to read the cookies associated with the current document:

allCookies = document.cookie;

allCookies is a string that contains a semicolon-separated list of cookies. You can split this semicolon-separated string to get the individual cookies.

Something Talk About Cookies

In a simple scenario the web server instruct to client’s browser to write the some data in the form of a cookie. The browser writes that data in key value pair. If the browser writes cookies successfully than each time when the client arrives at another page on your site, the browser sends that stored cookie to the server with the request. So that on the Web Server you can read that cookie.

cookies between server and client

Cookie can be retrieved in the form of key1=value1;key2=value2…;keyN=valueN. Please make sure that the cookie string does not contain any commas, semicolons, or whitespace, you can use encodeURIComponent() and escape() JavaScript methods to avoid it.

Try this

Mozilla developers provide a simple and efficient framework to read and write the cookie with full unicode support in the JavaScript. You should also read this.