How to properly set/read a cookie in js-cookie library? - javascript

I just recently started trying to use the cookie library js-cookie:
Found here: https://github.com/js-cookie/js-cookie
I can't seem to determine whether my cookies are being set or read correctly. The main goal is to read if a checkbox is checked, create a cookie and use that on another page to change some elements.
Here's how I attempted setting the cookie:
$('#food').click(function() {
if ($(this).is(':checked')){
Cookies.set('food', 'true');
}
else{
Cookies.remove('food');
}
});
It properly reads the checkbox being checked on click, so I know it is at least reaching the cookie set.
For reading the cookie value:
if(Cookies.get('food') === 'true'){
$('#food').css("color", "#198a80");
}
I followed the documentation on the repository page for setting and it looks correct. I assumed reading the cookie just passed the value portion as a normal variable and it could be compared like normal, but the code just does nothing, so I guessed the problem was either with the setting or reading of the cookie.

Related

Cookie set with javascript disappears after refresh

I'm setting my cookies like this:
document.cookie = `${cookieName}=${JSON.stringify(cookieObject)};path=/;SameSite=Strict;Secure=true;expires=${someDate.toUTCString()};`
Everything is fine at first. But when I refresh, the cookie disappears and firefox console tells me a message:
Cookie “thecookiename” will be soon rejected because it has the “SameSite” attribute set to “None” or an invalid value, without the “secure” attribute.
If I refresh again, the message disappears and the cookie is also gone.
Chrome acts the same, but minus the message.
Edit
I realized, the problem might be related to the fact, that I'm overriding the document.cookie setter.
document.setCookie = document.__lookupSetter__('cookie');
document.newCookieSetter= (cookie) => {
// here I check, whether a cookie is allowed or not. Calls for an api endpoint to get the information.
if (cookieDataRecieved() && cookieIsAllowed(cookie)) {
return document.setCookie(cookie);
}
cacheCookie(cookie); // If cookie data has loaded, try checking again.
}
document.__defineSetter__('cookie', document.newCookieSetter);
The problem applies to every cookie added through the document.cookie = "somecookie";
The Secure attribute has no value, it's just a bare attribute (present or absent), so just replace Secure=true with Secure.

document.cookie returns only PHPSESSID=*random number*

I'm trying to get a cookie I have set but all I'm getting is the PHPSESSID.
I set my cookie in a separate PHP page with:
setcookie("username", $sentname, time()+(60*60*24*30),NULL,NULL,NULL,false);
I can then find it through firefox settings.
When I try to access it using JavaScript on a different page I use:
<script>
$(document).ready(function(){
var cookie = document.cookie;
alert(cookie);
});
</script>
which then returns:
PHPSESSID=gvjsgfd8etlbdq43lndni3o0g4
It should return all the cookies, only "username" so far, I have set in a key paired string. I tried using the jquery plugin for cookies and it returned the same thing. I also couldn't find this problem elsewhere online.
Not sure if I should delete the question but one of the related links gave me the answer.
The cookie path must be set to '/' to be accessible from all subdomains. so I changed it too:
setcookie("username", $sentname, time()+(60*60*24*30),'/',NULL,NULL,false);
which gives me:
PHPSESSID=gvjsgfd8etlbdq43lndni3o0g4; username=asdf

How to detect if cookie is set in Javascript ?

I have set a session in PHP, which is creating a cookie: PHPSESSID...
I can detect this in Chrome & Opera by using document.cookie. However in Forefox, document.cookie also returns cookies set on the page by other domains, e.g. Google Analytics.
In PHP I am setting the sessions like:
session_start();
$_SESSION['source'] = &$ref['source'];
$_SESSION['term'] = &$ref['term'];
session_write_close();
I need to be able to detect if this session is set in Javascript, by locating the cookie. What is the best way to go about this?
At the moment I am just using:
document.cookie.indexOf( 'PHPSESSID' )
which seems like a bit of a botch.
The document.cookie property will return all the cookies. While your indexOf will work, it will break if your cookies actual data contains 'PHPSESSID'. It will also match the following cookie 'MYPHPSESSIDIDIT', as it contains your cookie name.
You could parse the cookies with the following function (not tested):
function getCookieValue(name)
{
// find cookie entry in middle?
var s=document.cookie,
c=s.indexOf("; "+name+"=");
if(c==-1)
{
// no, is it at the start?
c=s.indexOf(name+"=");
if(c!=0) return null;
}
// get length of value
var l=c+name.length+1,
e=s.indexOf(";",l);
// is it at the end?
if(e==-1) e-s.length;
// cut out the value
return s.substring(l,e);
}
Hope this helps
Use this Jquery plugin, it's so cool.
https://github.com/carhartl/jquery-cookie
You can use it like this way:
if($.cookie('PHPSESSID') != undefined){
//PHPSESSID exists
}

Check for undefined javascript variable?

I am trying to check if a variable is defined, if it is then an ajax request is run...If it is not I want the user to be redirected to a separate page where the variable is set.
for example I want something like this:
// if variable is undefined
if (typeof accessKey === 'undefined') {
alert('the variable is not set!');
} else {
var accessKey = 'some random string generated from google';
alert('the variable is set!');
proceed to refresh the page and run through check again.
}
So the first time the page is run, it checks if the variable is set. If the variable is not set it will set the variable and then reload the page and run through the check again.
Problem is 'accessKey' always returns undefined but the code runs through as if the variable is defined. Why?
If the variable is not set it will set the variable and then reload the page [emphasis mine] and run through the check again
There is your problem: variables (or any other piece of js code) do not persist between page reloads.
If you need stuff to persist, you have to use one of these:
Server-side sessions or databases (using ajax to pass data to the server and persist it there)
Client-side storage (such as localStorage).
Cookies (can be generated at client-side or server-side)
Save the value in hiddenfields or in cookie.

Create a javascript msgbox (YES/NO) and get results in code-behind

Is it possible to create a (yes/no) javascript messagebox from code-behind, and also retrieve the return values?
I would like to set the content of a session object based on the client Yes/No.
The idea is to use this approach for redirecting iphone clients from my default web page.
"Do you want to go the iphone version of this site?"
--YES Redirect to "iphone" default page, and set a session object to avoid asking this question again if default page is requested again
within the lifespan of the session object.
--NO Set a session object to avoid asking this question again if default page is requested again within the lifespan of the session
object.
Just display the message and set an appropiate cookie. Then make your server-side react to the cookie and render the selected version of the site.
http://www.htmlite.com/JS006.php - Javascript Confirm popup
http://www.w3schools.com/js/js_cookies.asp - Javascript cookies
In Code behind on FormLoad or wherever it best suits your needs, you would just have to set your button's OnClientClick as follows:
button.OnClientClick = "IphoneVersion()";
In Markup create a function in javascript as follows:
function IphoneVersion() {
if (confirm('Do you want to go the iphone version of this site?')) {
//set hidden value here }
else { //don't set hidden value }
}
You can set your Hidden control value to yes/no text and refer to it behind code or you can redirect in the function itself.
That will do it!
Or you could stash the value in a hidden field and read it on the server side.
** EDIT **
OP Comment:
I would like to set the content of a session object based on the client Yes/No.
Either way you look at it, if he wants to set this value in session, he has to go back to the server.
Try something like this:
confirmSomething = function(){
__doPostBack("<%=Button1.ClientID%>", confirm("Are you sure?"));
}
<asp:Button ID="Button1" runat="server" OnClientClick="confirmSomething();" />
Code-behind:
protected override void RaisePostBackEvent(IPostBackEventHandler source, string eventArgument)
{
bool conf = bool.Parse(eventArgument);
}

Categories