Reputation: 2679
I am learning to create cookies in JavaScript, I am having problems in understanding the working of last 3 lines of code. I know this Question doesn't suits the Stackoverflow Standand but I will be grateful if anyone kindly explains it.
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;
}
Upvotes: 0
Views: 100
Reputation: 1140
Well said by ustun, if you understand the general format for writing and retrieving the cookie then you can be a master in it. It's just as simple as like handling Strings and arrays.
Cookies are very useful component for storing the small sized infrequent content. Normally it's used for transferring the small amount of data(like current user name, or the users unique ID & so) from one page to another page or to communicate with a server for specific operations.
Setting The Cookie
Setting up the cookie is normally very easy. It just require three part in it's definition.That they are,
document.cookie = "name = test ; expires = date ; path =/"
var myCookie = document.cookie.split(';');
for(var i=0;i < myCookie.length;i++) {
var cookieValue = myCookie[i];
var pair = myCookie[i].split('=');var key = pair[0];var value= pair[1];
}
Limitation Even it's very handy to use but they are not meant as a normal communication or mechanism. Note that web browsers are not required to save more than 300 cookies total, nor more than 20 cookies per web server (for the entire server, not just for the page or site on the server), nor to retain more than 4 kilobytes of data per cookie (both name and value count towards this 4 kilobyte limit). The biggest limitation of these is the 20 cookies per server limit, and so it is not a good idea to use a different cookie for each variable that has to be saved. Rather save a single cookie containing a lot of information.
Upvotes: 0
Reputation: 7041
If exdays is not null, i.e. it is given as an argument (in JavaScript, functions can take any number of arguments), with a ternary check (if/else shorthand) it appends the string "expires=..." to the cookie string. Else, there is no expires string (it will be a session cookie).
Finally, document.cookie is modified. For more info on cookies and changing via JS, see www.quirksmode.org/js/cookies.html
Basically, to add a new cookie using JS, you set document.cookie = "key=value". Other cookies are not overwritten, the new cookie is simply appended.
To delete other cookies, one needs to set an expiry date in the past and they will be cleared by the browser.
If you simply print document.cookie, you will see all cookies (technically not all, except http-only cookies etc.), but there is no way to learn their expiry dates from JavaScript.
Upvotes: 4