Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update and delete a cookie?

I need help to know how to update values and how to delete a cookie created from this code! I'm new to JavaScript so it's great if anyone can help me.

function getCookie(c_name) {      var i,x,y,ARRcookies = document.cookie.split(";");      for (i=0;i<ARRcookies.length;i++) {           x = ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));           y = ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);           x = x.replace(/^\s+|\s+$/g,"");           if (x==c_name) {               return unescape(y);           }       } }  function setCookie(c_name,value,exdays) {     var exdate = new Date();     exdate.setDate(exdate.getDate() + exdays);     var c_value = escape(value) + ((exdays==null) ? "" : ";                                    expires="+exdate.toUTCString());    document.cookie=c_name + "=" + c_value;  }  function check2Cookie() {      var username=getCookie("username");      if (username!=null && username!="") {          username= "0";          setCookie("username",username,1000);      }      else {          username=" ";          if (username!=null && username!="") {                username= "0";                setCookie("username",username,1000);          }      } } 

This is the code for cookie creation.

Code for creating is setCookie("username",username,1000);

Now how to update this cookie and delete this cookie.

like image 653
San Jay Avatar asked Aug 27 '11 15:08

San Jay


1 Answers

The cookie API is kind of lame. Let me clarify...

You don't update cookies; you overwrite them:

    document.cookie = "username=Arnold"; // Create 'username' cookie     document.cookie = "username=Chuck"; // Update, i.e. overwrite, the 'username' cookie to "Chuck" 

You also don't delete cookies; you expire them by setting the expires key to a time in the past (-1 works too).

Source: https://developer.mozilla.org/en-US/docs/Web/API/document.cookie

like image 141
jordanb Avatar answered Sep 20 '22 20:09

jordanb