// 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' );
}
?>
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);
}
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]
}
They updated the page today so everything in the page should be latest as of now.
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.
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>
I'm sure this question should have a more general answer with some reusable code that works with cookies as key-value pairs.
Asked 9 years, 5 months agoModified Viewed 1.4m times678197This question already has answers here: (24 answers)Closed 7 years ago.
Follow12811 silver badge1313 bronze badgesasked Jan 28, 2013 at 23:347,05977 gold badges1919 silver badges1919 bronze badges
9kaka = "Css=document.getElementById("css").href" + kakdatum; is a syntax error. –
what i wonder is how to set cookie based on a choice. If i choose a specific css file, then i want that file to be saved and activated the next time i open the html file –
@DrWooolie How about marking an answer correct so visitors to this question will find the best answer? The top answer clearly isn't the best. –
Now (2017), some use cases make investigating the , as opposed to cookies, worthwile. –
A concise but fully featured modern approach to get/set cookies over at the duplicate question: –
Source -
Follow2,4631616 silver badges2626 bronze badgesanswered Jun 8, 2014 at 6:2814.4k44 gold badges2727 silver badges2424 bronze badges
7toGMTString() is deprecated - just FYI. –
14This won't work if your cookie contains a semicolon. –
7Why so complex? Use date.setDate(date.getDate() + days); instead –
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=/'. –
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; –
28The expires variable is obsolete although still supported by browsers. Use max-age instead! –
61It looks like IE8 and below do not support max-age, so expires is the safer choice. –
5There's also a domain param you can set on cookies which is useful if you want to use a cookie across different sub domains on your site. –
2Dont work on Chrome. See here why: –
2Note that the MDN reference page mentions nothing about expires being deprecated/obsolete. That's because it can, on occasion, serve a purpose not covered by max-age. The value of max-age must be a numerical value interpreted as an amount of seconds, while the expires value can be set to the special value Session which is not the same as max-age=0;. –
38
Check for setting and getting cookie values via JS.
Follow6,32466 gold badges5555 silver badges7373 bronze badgesanswered Jan 29, 2013 at 0:2077844 silver badges33 bronze badges
13@BT could you elaborate on what about the above code is out of date and misinformed? –
14@BT, I've yet to see a reference on w3schools that is out of date or contains incorrect information. –
17-1 for w3schools –
10I just checked our analytics, and 10% of our IE users still use IE8 or lower. So using 'max-age' is a pretty bad idea. –
18Stupidness!! +1 for the working example, I don't actually see a problem with w3schools, –
36
This snippet is taken from and probably is trustable. This is UTF-safe object for work with cookies:
There is an alternative snippet :
FollowBot111 silver badgeanswered Jun 4, 2014 at 11:0952.7k3939 gold badges111111 silver badges150150 bronze badges
6Just a word of warning @SandipPingle, the code provided in this answer is actually GPL licensed. –
@MarcinHabuszewski thanks for pointing out. How can I use this code then(my app is not GPL licensed)? –
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. –
18GPL or not, I prefer code I can read. –
setItem does not work for me. I tested it on chrome. the other methods work fine. –
Not the answer you're looking for? Browse other questions tagged or .