Web Technologies - Old Questions

7.  What are the important uses of cookies? Give some examples.

5 marks | Asked in 2069

A cookie is a variable that is stored on the visitor's computer. Cookies let you store user information in web pages.

When a web server has sent a web page to a browser, the connection is shut down, and the server forgets everything about the user. Cookies were invented to solve the problem "how to remember information about the user".

  • When a user visits a web page, his/her name can be stored in a cookie.
  • Next time the user visits the page, the cookie "remembers" his/her name.

Cookies are saved in name-value pairs like:

    username = Ronaldo

When a browser requests a web page from a server, cookies belonging to the page are added to the request. This way the server gets the necessary data to "remember" information about users.

JavaScript Cookies

E.g.

JavaScript code to set and get a cookie:

<!DOCTYPE html>  

<html>  

<head>  

</head>  

<body>  

<input type="button" value="setCookie" onclick="setCookie()">  

<input type="button" value="getCookie" onclick="getCookie()">  

    <script>  

    function setCookie()  

    {  

        document.cookie="username=Jayanta";  

    }  

    function getCookie()  

    {  

        if(document.cookie.length!=0)  

        {  

        alert(document.cookie);  

        }  

        else  

        {  

        alert("Cookie not available");  

        }  

    }  

    </script>  

</body>  

</html>