Does Javascript have a higher level API for accessing cookies? - javascript

All the cookie handling examples I've seen for Javascript treat cookies as a string and do their own splitting and parsing etc.
Before I do this myself by hand, I want to check that there isn't a higher level API already available in, say, HTML5 / new javascript, for treating cookies as an associative array or something.
Is there?

Natively no. The document.cookie property holds the cookies, as a string, as you mention, and simply sends that string in the Cookie request header of the requests.
Then, wherever you need these cookies to be parsed (either on the client by accessing the document.cookie or on the server by accessing the Cookie request header), you have to implement your own parser or use one built already.
For storing things on the client side, you can use localStorage:
localStorage.setItem("foo", "42");
localStorage.getItem("foo");
// => "42"
But again, the server has no access to the localStorage.

Related

java session in servlet the same as sessionstorage in javascript

I have a servlet which I call the following:
request.getSession().setAttribute("name", nameObj);
Can I access it from the following page using
console.log('IH HERE' + sessionStorage.getItem('name') );
It doesn't seem to work. Either js or jquery solution would be nice.
Thanks,
Scott
This won't work, for two reasons:
sessionStorage is client-side only; it's not sent to the server via HTTP requests and the server can't write it without talking to the client.
request.getSession() is server-side only, with a session ID stored in a cookie but nothing else stored in a client-accessible format.
You'll have to use cookies if you want to achieve this effect (read / write by both) or loop over the session and provide it all in the page somewhere (read only by client).

When to create cookies at client side(browser)

I understand the importance of creating cookies at server side , it is for transferring information between server and browser ,since HTTP is stateless protocol.
But I am not aware about why and when cookies are created at client side (browser).
Hope my question makes sense.
But I am not aware about why and when cookies are created at client
side (browser).
Because if you want to save for example settings for the user you can use cookies. It might be easier as setting them in php $_COOKIE (serverside).
BUT make sure it is no data which contains password or similiar - cookies can be shown in the browser
document.cookie = "name=value";
document.cookie = "username=smith"; // setting two cookies
document.cookie = "lastlogin=Dec 1 2045";
...
alert(document.cookie); "username=smith; lastlogin=Dec 1 2045"
JS has a global document.cookie field (which is a magical string with
odd behavior) when you assign into document.cookie, it actually
appends / concatenates a new cookie (an unfortunate syntax that does
not match the expected semantics of the = operator)
This can be for many reasons. I use cookies on the client side to store non-sensitive information about the user that may be useful to know the next time they access the site.
For example if I am building a shopping website. I could ask the user to pick a currency and store that in a cookie so next time the user accesses the website I can read that cookie and set the currency without prompting the user.
Often, client-side cookies is used to store key to extract stored information from database or other storage
http://screencast.com/t/mzvp9jTP

Best way To handle a Cookie

i am newbie at developing web Application and like to learn best practices
i want to know what is the best practise to handle the cookie data should one use JavaScript or PHP to handle a cookie data?
1.Do you use javascript to get cookie and than pass it to PHP to do all the filtering ?
2.Do you use PHP to do all of the stuff?
3.Which one of the above will improve performance or is there another way?
should one use JavaScript or PHP to handle a cookie data?
To make this a little more general, let's call this "Client side" (which is almost exclusively JavaScript) and "Server side" (which can be PHP, JavaScript or any other language) code.
The short answer is that: It depends what you are doing with the cookie data.
Most of the time, dealing with cookies server side is simpler.
Sometimes, the information in the cookie needs to be secure, and you don't need to access it from client side code, so you'll set an http only flag on it so that if you suffer an XSS attack the damage is limited.
Sometimes you will want to avoid making a server round trip (to take a trivial example: You allow the user to pick different stylesheets for your website. You don't want to reload the entire page when their change their preference. You use client side code to change the stylesheet currently loaded, and client side code to store that preference in a cookie. In the future, when other pages are loaded, you can use server side code to set a different <link> element.)
Do you use javascript to get cookie and than pass it to PHP to do all the filtering ?
You might use client side code to set a cookie value, and then use server side code to read it. There is no point in using JavaScript to read it and then using some non-cookie based mechanism to send it to server side code. That just makes things complicated and more likely to go wrong.
Do you use PHP to do all of the stuff?
Only if all the stuff is better done with PHP
Which one of the above will improve performance or is there another way?
As is normal with questions of client side code vs server side code: If you aren't loading a new page anyway, then using client side code is usually faster.
It depends on the type of application.
If your application is full request based with PHP as backend, then use can PHP tot extract cookies.
check this link http://www.w3schools.com/php/php_cookies.asp
Or, if you application follows REST architecture or you want send data to the backend using Ajax. Then use javascript/Jquery to get cookie value and send it to the backend server that is PHP or in any other language.
Check this link to know, how to access cookies using jquey.cookie.js plugin:
https://github.com/carhartl/jquery-cookie
In handling cookies, it does not really matter whether you use javascript or PHP, it just depends on when it is more beneficial to access/manipulate them. Server-side stuff always seems more secure, but cookies are always accessible, client or server-side, so it doesn't really matter. You can create a cookie in PHP like this:
setcookie($cookieName, $cookieValue, time() + 3600);
That sets a cookie for an hour, you can then access it through the $_COOKIE superglobal array with array notation, for example
$var = $_COOKIE[$cookieName];
However, keep in mind that this won't work if cookies aren't enabled in the browser, such as when someone uses incognito mode.
In javascript, you can set cookies like this:
document.cookie="cookiename=cookievalue";
However, cookies in javascript are all concatenated as one big string in document.cookie, so the way to break them up into a normal array is with the split function, for example:
var arr = [];
function getCookieArray() {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
You can find more about that here http://www.w3schools.com/js/js_cookies.asp
So, remember, that cookies are not for storing sensitive data. They're often used to store preferences, but never anything that people shouldn't be able to have access to.

Getting Cookie for a website for a User

Is it possible to search a web page's cookie files for the cookies corresponding to a particular user?
For Example, given any of the functions defined here, I hope to be able to pass in a website URL and a name and function returns the cookie for that user(if any); All this happening when I run the script.
Or, how can I get the username from the cookies collected?
Also, When I run commands like document.cookie, it returns a dialog with some variables and values. Variable like localle, c_user, csm, sub, act, etc... What is the meaning of these variables? Is it possible to uniquely identify a cookie given the a username?
JavaScript, when embedded in an HTML document, has access to the cookies the browser has set for that page.
It cannot access cookies for a different page (unless the cookie is shared between them).
It cannot access cookies for other browsers (since the cookies are not stored in the browser running the JS).
Update re edit (which, BTW, should have been a new question):
document.cookie gives you a string containing the cookies for the document. The cookie names are determined by the author of the code that set them. They mean whatever that person wants them to mean.
Cookies can be identified by their name. Cookies do not have usernames (although the author of the code that set the cookie might store a username in a cookie).

Persist javascript variables between GET requests?

ASP .NET is allowed
Storing the values in hidden input fields is allowed
Query String is not allowed
POST request is not allowed
It is possible to store JS variables between GET requests ?
I want to reinitialize them on the client using ClientScript.RegisterStartupScript
Can I use cookies for this ?
Are there other posibilities?
Where cookies are stored when Request is made ?
Can I use cookies for this ?
Yes, see this tutorial on using cookies in Javascript.
Are there other posibilities?
If you are not allowed to append anything the URL of your requests, I can't come up with any.
Where cookies are stored when Request is made ?
In the HTTP request header. The aforementioned tutorial will tell you how to read their values from Javascript. On the server side with ASP.Net, you can read cookie values using Request.Cookie["cookieName"] which returns an instance of HttpCookie.
I wouldn't highly recommend this, but the other option is to alter the window.name property.
You can save some minor bits of data here, then retrieve them on the next page load.
Pros:
Quick-n-dirty, but works
Cons:
Messes up any window references for popups/child iframes
Since its a "hack", browser vendors may break this "feature" in the future
Of course if you can exclude all the old browsers, then use Global/Client Session Storage!
At the moment using cookies is your best bet. You can serialize the JavaScript objects to strings, and unserialize them back into objects later. A good choice format is JSON, since it is a subset of JavaScript.
There is also storing objects in Flash.
Storing in Google Gears.
DomStorage
See this library that has an interface to each:
http://pablotron.org/?cid=1557
If you are in control of all aspects of the page, then you can also wrap the page in a top level frame. Then only refresh the child frame. You can then store content in the parent frame.
You can see this used in sites like GMail, and others where the only thing that changes in the URL is outside the #.
You don't even have to change the URL, that part is just put in for Human Friendly URLs. (So you can actually copy and paste URLs as is).

Categories