·  JavaScript – Syntax – Terms – Cookie

 

- Info:

  - Cookie is peace of information stored on client computer.

  - It has expiry date and path which defines for which web pages should be sent.

 

- Example:

  - Property document.cookie behaves differently depending if you are storing or retreiving data, as example shows.

    It returns all cookies name-value pairs, for given path, separated by ';'.

  - Create C:\inetpub\wwwroot\Test.html

  - http://localhost/Test.html

 

    Test.html

    <script>

      document.cookie = 'username=ivor; expires=Fri, 27 Jul 2013 02:47:11 UTC; path=/';

      document.cookie = 'password=1234; expires=Fri, 27 Jul 2013 02:47:11 UTC; path=/';

      document.write(document.cookie); //deviceorder=012346578; device=0; username=ivor; password=1234

    </script>

 

    output

    deviceorder=012346578; device=0; username=ivor; password=1234

 

- Example:

  - This example shows helper functions for easier cookies manipulation.

  - Create C:\inetpub\wwwroot\Test.html

  - http://localhost/Test.html

 

    Test.html

    <script>

   

      //GET COOKIE.

      username = readCookie("username");

      document.write(username);

      

      //SET COOKIE.

      createCookie("username","ivor",5);

   

      //REMOVE COOKIE.

      //eraseCookie("username")

   

      function createCookie(name,value,days) {

        if (days) {

          var date = new Date();

          date.setTime(date.getTime()+(days*24*60*60*1000));

          var expires = "; expires="+date.toGMTString();

        }

        else var expires = "";

        document.cookie = name+"="+value+expires+"; path=/";

      }

      

      function readCookie(name) {

        var nameEQ = name + "=";

        var ca = document.cookie.split(';');

        for(var i=0;i < ca.length;i++) {

          var c = ca[i];

          while (c.charAt(0)==' ') c = c.substring(1,c.length);

          if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);

        }

        return null;

      }

      

      function eraseCookie(name) {

        createCookie(name,"",-1);

      }

      

    </script>

 

 

- Errors:

  - I get null for output.

  - This error occurs if you call Test.html through Windows Explorer by calling file:///C:/inetpub/wwwroot/Test.html.

    For above examples to work you have to access Test.html through Web Server by calling http://localhost/Test.html.