Example Cookie full (ok)

// functions cookie
function create_cookie(name, value, days) { 
    if (days) { 
        var date = new Date(); 
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); 
        var expires = "; expires=" + date.toGMTString(); 
        document.cookie = name + "=" + value + expires + "; path=/"; 
    } else { 
        document.cookie = name + "=" + value; 
    } 
}

function get_cookie(cname) {
    var name = cname + "=";
    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);
        if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
    }
    return "";
}
function remove_cookie(name) {
    document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT; path=/';
}
// Xử lý front end
var client_location = 'hn';
create_cookie( 'client_location', client_location, 365 );
var client_location = get_cookie('client_location');
console.log(client_location);
// Kết qủa: hn
// Back end
<?php  
     if (isset($_COOKIE['client_location'])) {
		define ( 'LOCATION', $_COOKIE['client_location'] );
	} else {
		define ( 'LOCATION', 'cg' );
	}
?>

Ask QuestionAsked 9 years, 5 months agoModified 1 year, 11 months agoViewed 1.4m times678197This question already has answers here:How do I create and read a value from cookie with javascript? (24 answers)Closed 7 years ago.

I'm trying to set a cookie depending on which CSS file I choose in my HTML. I have a form with a list of options, and different CSS files as values. When I choose a file, it should be saved to a cookie for about a week. The next time you open your HTML file, it should be the previous file you've chosen.

JavaScript code:

function cssLayout() {
    document.getElementById("css").href = this.value;
}


function setCookie(){
    var date = new Date("Februari 10, 2013");
    var dateString = date.toGMTString();
    var cookieString = "Css=document.getElementById("css").href" + dateString;
    document.cookie = cookieString;
}

function getCookie(){
    alert(document.cookie);
}

HTML code:

<form>
    Select your css layout:<br>
    <select id="myList">
        <option value="style-1.css">CSS1</option>
        <option value="style-2.css">CSS2</option>  
        <option value="style-3.css">CSS3</option>
        <option value="style-4.css">CSS4</option>
    </select>
</form>

javascripthtmlcsscookiesShareImprove this questionFollowedited Mar 1, 2018 at 21:53user avatarAaron Martin12811 silver badge1313 bronze badgesasked Jan 28, 2013 at 23:34user avatarDrWooolie7,05977 gold badges1919 silver badges1919 bronze badges

Show 1 more comment

4 Answers

Sorted by:Trending sort available Highest score (default) Trending (recent votes count more) Date modified (newest first) Date created (oldest first) 1053

I find the following code to be much simpler than anything else:

function setCookie(name,value,days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "")  + expires + "; path=/";
}
function getCookie(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) {   
    document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}

Now, calling functions

setCookie('ppkcookie','testcookie',7);

var x = getCookie('ppkcookie');
if (x) {
    [do something with x]
}

Source - http://www.quirksmode.org/js/cookies.html

They updated the page today so everything in the page should be latest as of now.

ShareImprove this answerFollowedited Jul 12, 2020 at 14:27user avatarFakhruddin Ujjainwala2,4631616 silver badges2626 bronze badgesanswered Jun 8, 2014 at 6:28user avatarMandeep Janjua14.4k44 gold badges2727 silver badges2424 bronze badges

  • 7toGMTString() is deprecated - just FYI. ReferenceKeith W. Nov 20, 2015 at 19:48

  • 14This won't work if your cookie contains a semicolon. – lucaswxp Jan 11, 2016 at 21:31

  • 7Why so complex? Use date.setDate(date.getDate() + days); instead – dude Mar 8, 2018 at 15:22

  • 5The eraseCookie function didn't work for me (FireFox Developer Edition 66.0b4). Instead, I had to use the code from B T's answer: document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/'. – ban-geoengineering Feb 1, 2019 at 20:28

  • 4Nice answer. While using semicolon(;) in cookie value I have got problem. So I refined some lines. Please update in your answer. From function setCookie(name,value,days) document.cookie = name + "=" + (encodeURIComponent(value) || "") + expires + "; path=/"; From function getCookie(name) if (c.indexOf(nameEQ) == 0) return decodeURIComponent(c.substring(nameEQ.length,c.length)); Use encodeURIComponent(), decodeURIComponent() in retutn statement; – KarthikeyanMlp Mar 1, 2019 at 13:36

Show 19 more comments424

These are much much better references than w3schools (the most awful web reference ever made):

Examples derived from these references:

// sets the cookie cookie1
document.cookie = 'cookie1=test; expires=Sun, 1 Jan 2023 00:00:00 UTC; path=/'

// sets the cookie cookie2 (cookie1 is *not* overwritten)
document.cookie = 'cookie2=test; expires=Sun, 1 Jan 2023 00:00:00 UTC; path=/'

// remove cookie2
document.cookie = 'cookie2=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/'

The Mozilla reference even has a nice cookie library you can use.

ShareImprove this answerFollowedited Aug 3, 2020 at 11:35user avatarlin17.5k44 gold badges5555 silver badges8282 bronze badgesanswered Jul 8, 2013 at 8:18user avatarB T53k3434 gold badges176176 silver badges200200 bronze badges

Show 2 more comments38

Check JavaScript Cookies on W3Schools.com for setting and getting cookie values via JS.

Just use the setCookie and getCookie methods mentioned there.

So, the code will look something like:

<script>
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 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 cssSelected() {
    var cssSelected = $('#myList')[0].value;
    if (cssSelected !== "select") {
        setCookie("selectedCSS", cssSelected, 3);
    }
}

$(document).ready(function() {
    $('#myList')[0].value = getCookie("selectedCSS");
})
</script>
<select id="myList" onchange="cssSelected();">
    <option value="select">--Select--</option>
    <option value="style-1.css">CSS1</option>
    <option value="style-2.css">CSS2</option>
    <option value="style-3.css">CSS3</option>
    <option value="style-4.css">CSS4</option>
</select>

ShareImprove this answerFollowedited Sep 24, 2016 at 9:41user avatarStacked6,32466 gold badges5555 silver badges7373 bronze badgesanswered Jan 29, 2013 at 0:20user avatarMunish Poonia77844 silver badges33 bronze badges

Show 4 more comments36

I'm sure this question should have a more general answer with some reusable code that works with cookies as key-value pairs.

This snippet is taken from MDN and probably is trustable. This is UTF-safe object for work with cookies:

var docCookies = {
  getItem: function (sKey) {
    return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
  },
  setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
    if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
    var sExpires = "";
    if (vEnd) {
      switch (vEnd.constructor) {
        case Number:
          sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
          break;
        case String:
          sExpires = "; expires=" + vEnd;
          break;
        case Date:
          sExpires = "; expires=" + vEnd.toUTCString();
          break;
      }
    }
    document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
    return true;
  },
  removeItem: function (sKey, sPath, sDomain) {
    if (!sKey || !this.hasItem(sKey)) { return false; }
    document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + ( sDomain ? "; domain=" + sDomain : "") + ( sPath ? "; path=" + sPath : "");
    return true;
  },
  hasItem: function (sKey) {
    return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
  },
  keys: /* optional method: you can safely remove it! */ function () {
    var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
    for (var nIdx = 0; nIdx < aKeys.length; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
    return aKeys;
  }
};

Mozilla has some tests to prove this works in all cases.

There is an alternative snippet here:

ShareImprove this answerFollowedited Jun 4, 2014 at 14:20user avatarCommunityBot111 silver badgeanswered Jun 4, 2014 at 11:09user avatarDan52.7k3939 gold badges111111 silver badges150150 bronze badges

  • 6Just a word of warning @SandipPingle, the code provided in this answer is actually GPL licensed. – jahu Aug 9, 2014 at 16:03

  • @MarcinHabuszewski thanks for pointing out. How can I use this code then(my app is not GPL licensed)? – Sandip Pingle Aug 11, 2014 at 5:55

  • 8@SandipPingle That's the "charm" of GPL, you can't (unless you turn your app GPL). This code is somewhat similar to a generic solution to the problem, so it begs for a question: can generic code actually be licensed (or is such license valid in case of generic code)? Try using different (non-GPLed) code to solve your problem. – jahu Aug 11, 2014 at 11:38

  • 18GPL or not, I prefer code I can read. – Cypher Mar 12, 2015 at 0:15

  • setItem does not work for me. I tested it on chrome. the other methods work fine. – IgniteCoders Jun 22, 2015 at 16:34

Show 5 more comments

Not the answer you're looking for? Browse other questions tagged javascript html css cookies or ask your own question.

Last updated