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.
- function setCookies(){
-
- var firstName=document.getElementById('firstname').value;
-
- if(firstName!=""){
- debugger
- document.getElementById('firstname').value=firstName;
- document.cookie="fname = "+firstName+";"
- }
- }
-
- window.onload=function(){
-
- var cookiearray=document.cookie.split('=')
- document.getElementById('firstname').value=cookiearray[1]
- }
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?
- document.cookie="fname = "+firstName+"; expires=Mon, 17 Feb 2020 00:21:00 UTC;";
How to read cookies?
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?
- 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.