how to use cookies in JQuery - javascript

It is easy to use cookies in serverside like PHP,.NET...etc
I would like to use cookies for static website which is just HTML, CSS & JQuery .
Anybody know how to implement cookies in JQuery ?

the jQuery Cookie plugin is one way to go:
https://github.com/carhartl/jquery-cookie
You use it like so:
$.cookie('cookie_name', 'value'); // to set
$.cookie('cookie_name'); // to get

You can use this plugin
example: to set a cookie
$.cookie("example", "foo");

You don't need a jQuery plugin, you can easily access cookies in JavaScript. Here's how: https://developer.mozilla.org/en/DOM/document.cookie
But maybe the plugins linked in the other answers will give you easier access.

Are you sure that cookie is exactly what you need? There are localStorage which is much better in many scenarios.
You wrote that you want use cookies with static website, but cookies will be sent to the server and returned back. Is it really needed that you sent the information to the server on leading the static website? It increases the size of HTTP header and decreases the performance of the web site (see here for example).
Cookies have very hard restrictions. Corresponds to the section 6.3 of rfc2109 or 6.1 of rfc6265: At least 4096 bytes per cookie, at least 50 cookies per domain (20 in rfc2109), at least 3000 cookies total (300 in rfc2109). So the cookies one can't use to save too many information. For example if you would save state of every grid of every your web page you can quickly achieve the limits.
If you just want to save some users preferences for the page you can use localStorage and the usage is really easy.
If you prefer to use some jQuery plugin instead of direct usage of localStorage and if you need support old web browsers (like IE6/IE7) then you can use jStorage for example. In the case you has only less size of storage: 128 KB instead of 5 MB (see here and IE userData Behavior), but it's better as 4K which one has for cookies (see here).
I want that you just think a little about alternatives to cookies.

Read Cookie:
var cookieValue = $.cookie("cookieName");
Write Cookie:
$.cookie("cookieName", "CookieValue");

You can use plain JS by accessing document.cookie.
See: http://jsfiddle.net/ShsYp/
Also: https://developer.mozilla.org/en/DOM/document.cookie

A simple, lightweight jQuery plugin for reading, writing and deleting cookies.For details demo and example see a link.https://github.com/carhartl/jquery-cookie

Related

How to set cookies client-side taking into account Intelligent Tracking Protection?

According to this blog post on webkit.org, cookies set client-side using document.cookie are capped to a 7 day expiry.
I understand the rationale behind using httpOnly for sensitive cookies such as auth tokens, but if I need to store something for a long duration and have it available across subdomains of a site, then cookies are the only option, right?
With these new ITP restrictions, setting cookies client-side which should live for any longer duration of time is not going to work, so what's the best way to approach this? One idea was make a route which takes params and converts them into a Set-Cookie header and then make a request to that instead of using document.cookie. Is there a better way?
One attempt would be to use localStorage instead of cookies, technically they don't expire. The Problem however can be, that the user can decide to empty the localStorage.
Here's an example
//use this if you only need it for the current page and remove it after leaving the page
const exampleStorage = window.localStorage;
exampleStorage.setItem('currentUser', 'Manuel');
//use this if you need to keep it even after leaving the page
localStorage.setItem('glob_currentUser', 'Max');
//and finally this if you need to keep it only for the session
sessionStorage.setItem("session", "Morning")
If you need more Information about LocalStorage here are 2 helpful websites:
MDN Window​.local​Storage
The W3C Specification for localStorage

Is Cookies the best way?

I am using Joomla, and there are 2 Sections/Branches, when the user lands on the home page they will be asked where they wan to go to.
If they choose Section A i want the browser to remember their choice for future, however if they decide for some reason to visit Section B later, i want the browser to replace the Section A with B so that in future B will be remembered.
Is using cookies the right way, if so how could this be done, any help would be much appreciated.
If both section/branches are in same domain (or subdomains) cookies are a good way, but local storage can be a good option too.
The following link can help you to use cookies in Joomla http://blog.tormix.com/joomla/set-and-get-cookies-in-joomla-cms/
Today the moist preferred way is storing inside a localstorage and not inside cookie's
because cookies are sent vs every request and storage is not.
(https://developer.mozilla.org/en/docs/Web/API/Window/localStorage)
Also you can pick one of the libs from this article
And you can use modernizer to be compliant with the old browsers version.
Setcookie("path", "A", 3600*31*365); // Set cookie for about a year.
Echo $_cookie["path"]; // Read cookie
Setcookie("path", "B", 3600*31*365); // Replace the cookie with path B.

Why new js Fetch standard forbid response header name as 'Set Cookie 1 / 2'?

I'm very surpised that https://fetch.spec.whatwg.org/ standard doesn't allow to set cookie from server. I expected New Fetch will be awesome alternative of XHR thing, but...
Does anybody knows any official answer for it? Thanks in advance!
What you state is incorrect. The server can definitely set cookies, but as with XMLHttpRequest you cannot access them from the API. The only way to observe cookies from JavaScript is document.cookies and we decided not to increase the number of places since we haven't found a good way to do that, while also respecting cookie flags such as HttpOnly.

Age verification with just javascript and no cookies: how?

I'm building a website for a EU company that sells beer, and need an age verification splash screen. That's quite easy, and I have one in place already. I use a lightweight cookie plugin (cookie.js found on the excellent http://microjs.com) in the page header. This is more or less my set up:
JS (in <head> element)
if (cookie.get("agechecked")) {
document.documentElement.className += " agechecked";
}
CSS
.agechecker { display: block; width: 100%; height: 100%; ... }
.agechecked .agechecker { display: none };
Sadly, for few visitors the agecheck doesn't work properly. Some can't get past it, for others it pops up after every page load, and for some, cookies just don't work which means the checkbox 'remember me' is broken to them. I want to use an alternative route to at least make sure the agecheck doesn't prevent anyone from viewing the site completely.
I only have javascript to my disposal and don't want to use cookies. Since I'm quite sure the equivalent to a session is a cookie that expires after the browser closes - so that kind of limits my options to... yeah, what?
Alternatives I'm considering:
jStorage - but that relies on a framework such as jQuery or Prototype, meaning I'd have to load jQuery in the page header. That won't do;
The window.name method, combined with JSON to store data in the window name property, which is a bit too hacky for my taste, and also doesn't carry over to other tabs
I could check the referer (was the visitor already on another page on this domain?) which is a 90% guarantee he/she got through the agecheck
I couldn't find any real useful information here on stackoverflow, but I'm sure some of you have built age verifications. How did you solve these issues?
(edit: I know, I should build a form that actually posts to the server where I can store and retrieve information in a gazillion different manners, but just take it from me I have to rely on javascript. Can't help it)
HTML5 webstorage (localStorage) is a client-side persistency mechanism. For browser compatibility, see http://caniuse.com/#feat=namevalue-storage.
I read your question as you need a way to persist state across webpages without using cookies.
Here are a few choices:
Html5 local storage http://diveintohtml5.info/storage.html
data in the URL (http://example.com/app/agechecked/main)
data as a GET variable ( ?agechecked=1 )

JavaScript cookie setting used to work and stopped

In a nutshell, I have a web application which used to be able to set cookies just fine, but it no longer works. The really strange thing is I've used Chrome's debugger to follow what's going on, and it makes it all the way to the "document.cookie = " statement fine.
Further, I haven't changed anything except the content of the cookie (adding more information). I haven't modified the cookie setting logic at all, or even the parameters.
Here's the most recent version of my application: http://asmor.com/scripts/tsrand/alpha/
The relevant bit is lines 147-149, http://asmor.com/scripts/tsrand/alpha/init.js
cookie=JSON.stringify(opt)
log("Cookie: "+cookie);
$.cookie(cookieName, cookie, { expires: 365 });
opt is an object I'm using to store form element values. I convert the object into a JSON string and then store it. Here's an example of what cookie contains in this version of the program:
{"diseaseSelect":".5","soloGame":"checkbox:false","showLog":"checkbox:true","min_Setting":"0","max_Setting":"1","cardBarrowsdale":"Maybe","cardDoomgate":"Maybe","cardDragonspire":"Maybe","cardDreadwatch":"Maybe","cardFeaynSwamp":"Maybe","cardGrimhold":"Maybe","cardRegianCove":"Maybe","min_Thunderstone":"1","max_Thunderstone":"1","cardStoneofAgony":"Maybe","cardStoneofAvarice":"Maybe","cardStoneofMystery":"Maybe","cardStoneofScorn":"Maybe","cardStoneofTerror":"Maybe","min_Monster":"3","max_Monster":"3","cardAbyssal":"Maybe","cardAbyssalThunderspawn":"Maybe","cardBanditHumanoid":"Maybe","cardCultistHumanoid":"Maybe","cardDarkEnchanted":"Maybe","cardDoomknightHumanoid":"Maybe","cardDragon":"Maybe","cardElementalFire":"Maybe","cardElementalNature":"Maybe","cardElementalPain":"Maybe","cardEnchanted":"Maybe","cardEvilDruidHumanoid":"Maybe","cardGiant":"Maybe","cardGolem":"Maybe","cardHorde":"Maybe","cardHumanoid":"Maybe","cardHydraDragon":"Maybe","cardOoze":"Maybe","cardOrcHumanoid":"Maybe","cardTheSwarm":"Maybe","cardUndeadDoom":"Maybe","cardUndeadLich":"Maybe","cardUndeadPlague":"Maybe","cardUndeadSpirit":"Maybe","cardUndeadStormwraith":"Maybe","min_Guardian":"0","max_Guardian":"1","cardDarkChampion":"Maybe","cardDeathSentinel":"Maybe","cardGuardianofNight":"Maybe","cardGuardianofTorment":"Maybe","cardUnholyGuardian":"Maybe","min_Trap":"0","max_Trap":"1","cardTrapDeath":"Maybe","cardTrapDire":"Maybe","cardTrapDraconic":"Maybe","min_Treasure":"0","max_Treasure":"1","cardAmuletTreasure":"Maybe","cardFigurineTreasure":"Maybe","cardUlbricksTreasure":"Maybe","min_Hero":"4","max_Hero":"4","cardAmazon":"Maybe","cardBelzur":"Maybe","cardBlind":"Maybe","cardCabal":"Maybe","cardChalice":"Maybe","cardChulian":"Maybe","cardClan":"Maybe","cardDeep":"Maybe","cardDiin":"Maybe","cardDrunari":"Maybe","cardDivine":"Maybe","cardDwarf":"Maybe","cardElf":"Maybe","cardEvoker":"Maybe","cardFeayn":"Maybe","cardFlame":"Maybe","cardGangland":"Maybe","cardGohlen":"Maybe","cardGorinth":"Maybe","cardHalf-Orc":"Maybe","cardLorigg":"Maybe","cardOutlands":"Maybe","cardPhalanx":"Maybe","cardRedblade":"Maybe","cardRegian":"Maybe","cardRunespawn":"Maybe","cardSelurin":"Maybe","cardSidhe":"Maybe","cardSlynn":"Maybe","cardStoneguard":"Maybe","cardTempest":"Maybe","cardTerakian":"Maybe","cardTholis":"Maybe","cardThyrian":"Maybe","cardToryn":"Maybe","cardVerdan":"Maybe","cardVeteran":"Maybe","min_Village":"8","max_Village":"8","cardAmbrosia":"Maybe","cardAmuletofPower":"Maybe","cardArcaneEnergies":"Maybe","cardBanish":"Maybe","cardBarkeep":"Maybe","cardBattleFury":"Maybe","cardBlacksmith":"Maybe","cardBlessedHammer":"Maybe","cardBluefireStaff":"Maybe","cardBorderGuard":"Maybe","cardBurntOffering":"Maybe","cardChieftansDrum":"Maybe","cardClaymore":"Maybe","cardCreepingDeath":"Maybe","cardCursedMace":"Maybe","cardCyclone":"Maybe","cardDivineStaff":"Maybe","cardDoomgateSquire":"Maybe","cardFeast":"Maybe","cardFireball":"Maybe","cardFlamingSword":"Maybe","cardFlaskofOil":"Maybe","cardForesightElixir":"Maybe","cardFortuneTeller":"Maybe","cardFrostBolt":"Maybe","cardFrostGiantAxe":"Maybe","cardGlowberries":"Maybe","cardGoodberries":"Maybe","cardGreedBlade":"Maybe","cardGuardianBlade":"Maybe","cardGuide":"Maybe","cardHatchet":"Maybe","cardIllusoryBlade":"Maybe","cardLantern":"Maybe","cardLightstoneGem":"Maybe","cardMagiStaff":"Maybe","cardMagicMissile":"Maybe","cardMagicalAura":"Maybe","cardPawnbroker":"Maybe","cardPiousChampion":"Maybe","cardPolearm":"Maybe","cardPolymorph":"Maybe","cardQuartermaster":"Maybe","cardRecurveBow":"Maybe","cardSage":"Maybe","cardScout":"Maybe","cardShortBow":"Maybe","cardShortSword":"Maybe","cardSilverstorm":"Maybe","cardSkullbreaker":"Maybe","cardSoulGem":"Maybe","cardSoulJar":"Maybe","cardSpear":"Maybe","cardSpiritBlast":"Maybe","cardSpiritHunter":"Maybe","cardSpoiledFood":"Maybe","cardTavernBrawl":"Maybe","cardTaxCollector":"Maybe","cardThunderRing":"Maybe","cardTorynGauntlet":"Maybe","cardTownGuard":"Maybe","cardTrader":"Maybe","cardTrainer":"Maybe","cardWarhammer":"Maybe"}
Now, here's the oldest backed-up copy I have: http://asmor.com/scripts/tsrand/backup/2010-09-13/dev/
This copy still works.
Here's the cookie-setting logic from that copy, lines 130-132 http://asmor.com/scripts/tsrand/backup/2010-09-13/dev/scripts/init.js
cookie=JSON.stringify(opt)
log("Cookie: "+cookie);
$.cookie(cookieName, cookie, { expires: 365 });
And an example of what the cookie for that one contains:
{"guardianSelect":".5","trapSelect":"1","monstersSelect":"3","heroesSelect":"4","villageSelect":"8","soloGame":"checkbox:false","useConditions":"checkbox:true","showLog":"checkbox:true","setBase":"checkbox:false","setPromo":"checkbox:true","setWrathOfTheElements":"checkbox:false","cardAbyssal":"Maybe","cardDoomknightHumanoid":"Maybe","cardDragon":"Maybe","cardElementalNature":"Maybe","cardElementalPain":"Maybe","cardEnchanted":"Maybe","cardGolem":"Maybe","cardHorde":"Maybe","cardHumanoid":"Maybe","cardOoze":"Maybe","cardUndeadDoom":"Maybe","cardUndeadSpirit":"Maybe","cardDarkChampion":"Maybe","cardDeathSentinel":"Maybe","cardTrapDeath":"Maybe","cardTrapDire":"Maybe","cardAmazon":"Maybe","cardBlind":"Maybe","cardChalice":"Maybe","cardClan":"Maybe","cardDiin":"Maybe","cardDivine":"Maybe","cardDwarf":"Maybe","cardElf":"Maybe","cardFeayn":"Maybe","cardGangland":"Maybe","cardGohlen":"Maybe","cardLorigg":"Maybe","cardOutlands":"Maybe","cardRedblade":"Maybe","cardRegian":"Maybe","cardRunespawn":"Maybe","cardSelurin":"Maybe","cardThyrian":"Maybe","cardToryn":"Maybe","cardAmbrosia":"Maybe","cardAmuletofPower":"Maybe","cardArcaneEnergies":"Maybe","cardBanish":"Maybe","cardBarkeep":"Maybe","cardBattleFury":"Maybe","cardBlacksmith":"Maybe","cardClaymore":"Maybe","cardCreepingDeath":"Maybe","cardCursedMace":"Maybe","cardFeast":"Maybe","cardFireball":"Maybe","cardFlamingSword":"Maybe","cardForesightElixir":"Maybe","cardGoodberries":"Maybe","cardHatchet":"Maybe","cardIllusoryBlade":"Maybe","cardLantern":"Maybe","cardLightstoneGem":"Maybe","cardMagiStaff":"Maybe","cardMagicMissile":"Maybe","cardMagicalAura":"Maybe","cardPawnbroker":"Maybe","cardPolearm":"Maybe","cardSage":"Maybe","cardShortBow":"Maybe","cardShortSword":"Maybe","cardSpear":"Maybe","cardTavernBrawl":"Maybe","cardTaxCollector":"Maybe","cardTownGuard":"Maybe","cardTrainer":"Maybe","cardWarhammer":"Maybe"}
I'm using libraries for the JSON and for setting/getting the cookie. Both that early version and the latest use the exact same versions of the exact same libraries.
The only thing I can think of is that the cookie has gotten a bit more than twice as long. Before URI encoding, we're talking 4000 characters vs. 1800 characters. Also, I URI encoded the more recent cookie and manually set it myself, and the browser accepted it just fine, and my program loaded it just fine.
I'm completely out of ideas here. Help!
You should really store all this data in a session on the server if possible, rather than having a massive cookie. Then you can simply request data via AJAX or embed it in each page request.
Browsers are only required to provide 4KB of space per cookie, so if you're over that there's a chance it might not be stored.
4096-byte limit; otherwise entire cookie is discarded by IE.
http://support.microsoft.com/kb/306070

Categories

Resources