Cookies in JavaScript

Introduction

 
If you see that a web application works on HTTP protocol and the HTTP protocol is a stateless protocol, this means that when we request some data on the web page after filling some information on the webpage, the webserver does not remember anything about that request after processing that request. However, in our case, we want our web application to remember the user's choice.
 
This means that if I fill my first name on the page, after the subsequent request, the page should know what information I filled in that textbox. But the page doesn’t remember that. This happens because web pages use the HTTP protocol to serve the webpage and HTTP is stateless.
This means that after processing the request of the client, the webserver doesn’t remember the client settings. To remember this, we have several options, but one of the easiest and most common way is to use cookies.
  1. function setCookies(){  
  2.   
  3.     var firstName=document.getElementById('firstname').value;  
  4.    // alert(firstName);  
  5.     if(firstName!=""){  
  6.         debugger  
  7.         document.getElementById('firstname').value=firstName;  
  8.         document.cookie="fname = "+firstName+";"//expires=Mon, 17 Feb 2020 00:21:00 UTC;";  
  9.     }  
  10. }  
  11.   
  12. window.onload=function(){  
  13.   
  14.     var cookiearray=document.cookie.split('=')  
  15.     document.getElementById('firstname').value=cookiearray[1]  
  16. }   
What are Cookies?
 
Cookies are small text files that browser stores in the client's machine. It is a string of name-value pair which is separated by semi-column.
How do cookies save on machines?
  1. document.cookie="fname = "+firstName+"; expires=Mon, 17 Feb 2020 00:21:00 UTC;";  
How to read cookies? 
  1. var doc=document.cookie;  
What is the difference between expires and max-age attribute?
 
With expires attribute, you can set the expiry date. This expire attribute is obsolete and very few browsers support this attribute.
 
Max-age: this attribute you can set the expiry in time and seconds and most of them are supports.
 
You also save the JSON object in the cookie.
 
How to check if cookies are enabled or not?
  1. this.navigator.cookieEnabled  
The above statement returns true if a cookie is enabled.
 
How to check JavaScript is enabled or Not?
 
The easiest way to detect if Javascript is enabled or not is by using the noscript tag. The content in noscript is displayed only when Javascript is not enabled by the browser.