I had a project in my web design class this semester(I'm a newbie at this) and I've been working on a little side work in my free time. I've been trying to work with cookies and JavaScript. We didn't cover cookies very much in my class and I've been searching and searching for an answer to my current problem. Chances are, if you've ever responded to anything on this site about JavaScript and/or HTML, I've read it. As my title says, I'm having a problem where my cookie doesn't seem to save. On first load, the code works fine, then I reload the page and it doesn't recall the cookie value.
This is my cookie script:
var name;
if(document.cookie)
{
var q1=unescape(document.cookie);
var q2=q1.search("name");
if(q2!=(-1))
{
var n=str.split("name=");
var n1=n[1];
var n2=n1.split(";");
var q=n2[0];
name=q;
}
else
{
name=window.prompt("Please enter your name.");
document.cookie="name="+escape(name);
}
}
else
{
name=window.prompt("Please enter your name.");
document.cookie="name="+escape(name);
}
This is used once the rest of the page is loaded in:
document.writeln(name+"text stuff");
In the case of an incorrect value in the cookie, I've created this function that is called on via a button in the HTML:
function wrongPerson()
{
document.cookie="name=hooper; expires=Thu, 01 Jan 1970 00:00:01 GMT";
location.reload();
}
Sorry for such a long post, but I wanted to make sure the community had as much information as possible. Also, sorry about the poor formatting. I wasn't sure how to bring over my entire long thing of code and have the system allow it.
You need to set expire on your cookie script. If you don't put an expire date to your cookie it will recognize as a "one-time cookie". And after a reload or anything, it will disappear.
Set an expire to Wed, 01 Jan 2014 00:00:01 GMT
This is my personal opinion, but I rather use window.location.href = window.location.href; instead of location.reload();
Related
I'm using the Hapi framework for a Node.js application, and the Hapi framework comes with its own Cookie management tools, which i'm using for authentication.
The framework then sets a cookie named session, with a json value encoded to base64. The domain is set to example.com (not .example.com)
Now, the problem lies when i attempt to edit this cookie client-side, by doing the following
document.cookie = 'session=' + btoa(JSON.stringify(_decoded)) + "; path=/; domain=example.com";
This actually sets a duplicate cookie with the domain '.example.com'
I haven't asked Javascript to prepend the dot, and i cant seem to get rid of it.
I'm assuming that it is because of this dot, that the cookie is being duplicated. How do i set the domain without it automatically prepending a dot?
EDIT
I've given up on trying to remove the leading dot, and instead am trying to delete the old cookie and then create a new one. However i still end up with duplicate cookies!
Navigate to /login and enter login details
Redirected to /account and cookie set by server (WITHOUT Leading Dot)
Execute Javascript to delete and re-create cookie
1 cookie now exists and it has a Leading Dot before the domain
The above behaviour is good, however the following also happens, which is bad
Navigate to /login and enter login details
Redirected to /account and cookie set by server (WITHOUT Leading Dot)
Navigate to /example
Execute Javascript to delete and re-create cookie
2 cookies now exists, one with the leading dot(created by JS) and one without (created by server)
The code i'm using is
API.Session = {
Encoded : function () { return document.cookie.replace(/(?:(?:^|.*;\s*)session\s*\=\s*([^;]*).*$)|^.*$/, "$1")},
Decoded : function () { return JSON.parse(atob(this.Encoded()))},
Update : function (_decoded) {
document.cookie = 'session=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
document.cookie = 'session=' + btoa(JSON.stringify(_decoded)) + "; path=/; domain=example.com;";
}
}
API.Helpers.ShowAdvancedOptions = function () {
var s = API.Session.Decoded()
s.ShowAdvancedOptions = true
API.Session.Update(s)
}
Is by some chance the original cookie already present in this?
btoa(JSON.stringify(_decoded))
Cause from:
document.cookie
document.cookie is defined as:
a string containing a semicolon-separated list of all cookies
So it seems to me you are adding a new semicolon-separated value (new cookie) to that list (without removing the original cookie)
Ok, it's not that, have you tried this?
link
Sounds like the same problem you described
For anyone with a similar issue, this was eventually solved by dropping the domain property altogether. See other related question
I'm working on a project and I have to make a button to remember users selected specific page. It should work like a cookie, but I need some more information about how to save website page on cookies. The main part is when users clicks on a button, website remember users selection and when users enter after some time the same page, he will see his selection. And of course, if user push the button one more time, his selection deletes.
P.s. I'm new guy in coding so, your help will be useful for me.
Thanks in advance.
You can use browser storage for this
When user select some value:
localStorage.setItem("userSelection", "selection-value");
And when the user enter on page, you verify if userSelection exists:
var userSelection = localStorage.getItem('userSelection');
if ( userSelection ) {
// some action
}
See more: localStorage
Use any of these below to store user preferences
sessionStorage.setItem("sessionData", "I am set in session storage.");
localStorage.setItem("localData", "I am set in local storage.");
My recommendation is to store preference using URL hash combination while.storing in session or localstorage
you can do that based on ids like in my example right bellow
function getCookie(name){
var b=name+"=",
c=decodeURIComponent(document.cookie),
d=c.split(";");
for(var e=0;e<d.length;e++){
for(var f=d[e];" "==f.charAt(0);)f=f.substring(1);
if(0==f.indexOf(b))return f.substring(b.length,f.length)
}
}
function setCookie(name,value,period,path){
var time=new Date;
time.setTime(time.getTime()+1e3*(60*(60*(24*period))));
document.cookie=name+"="+value+";"+"expires="+time.toUTCString()+";path="+(path?path:"/")
}
function removeCookie(cookie_name){
if(getCookie(cookie_name)){
document.cookie=cookie_name+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
}
}
document.getElementById('xxx').onclick = function(){
if(getCookie(this.id)==1) {
removeCookie(this.id)
} else {
setCookie(this.id,1,999999);
}
}
<button id="xxx">Selection 1</button>
and of course use php or maybe javascript to detect if cookie exists.
What I am looking to achieve is that when a user comes to my site they immediately encounter a pop up (or a landing page) that asks, are you a man or a woman or other (choose x or y or z). They pick and click the link, then once they choose they go to that part of the site (and no it isn't a adult site ;). A cookie then remembers their choice and each time they return they are automatically redirected to their choice.
So basically we need the ability to set a cookie based on their choice (via link or form button) and then when they return to the homepage get that cookie and redirect.
I've seen some questions and answers that are close but just not quite there with this scenario and I end up confused.
What do you think? Doable? Please help and thanks so much.
Without knowing much of your architecture, I came up with the following:
This code should be called after the user has made the choice:
//´choice´ contains the value of what the user chose
//Setting the cookie:
document.cookie="gender="+ choice +"; expires=Thu, 18 Dec 2029 12:00:00 UTC";
//Redirect the user after the cookie has been set:
document.location.href = "http://yoursite.com/";
Take a look how cookies are defined in PHP: http://php.net/manual/en/function.setcookie.php
Then in PHP code you may read what cookies are set when the user loads your site:
if($_COOKIE["gender"] === "x"){
//Do some x stuff
} else if($_COOKIE["gender"] === "y") {
//Do some y stuff
}
In my asp.net application, am creating a cookie from server side using following code
Dim aCookie As New HttpCookie("StartDownload")
aCookie.Value = "True"
aCookie.Expires = DateTime.Now.AddMinutes(1)
Response.Cookies.Add(aCookie)
When I execute this code, the cookie is getting created, but am not able to delete the cookie from javascript on click of a button. Below is the javascript code.
function delCookie() {
alert(document.cookie);
document.cookie = "StartDownload" + "=; expires=" + new Date(0).toUTCString();
alert(document.cookie);
}
Am using IE browser. Not sure what the problem is. Kindly help.
You can try to hardcode the expiry date, something like, Thu, 01-Jan-1970 00:00:01 GMT and see if that'd work for you or not.
If still not, you might want to ask yourself following questions:
Have you checked the client-side and server-side cookie domains and paths to ensure they're the same?
Is one cookie secure and the other not?
Are there any server/client clock sync issues?
I'm having a bit of an issue deleting cookies in my JavaScript web-app. I've used this code in a separate function and it works just fine, but for some reason right now it doesn't actually change the expire time of the cookie for some strange reason, maybe I'm missing something obvious, but here's my code:
function deletetodo(obj) {
var checkboxID;
// get just the ID number of the checkbox.
checkboxID = obj.id.replace(/todo-status-/g, '');
// to make sure it's getting the right cookie ID (which it is)
alert(checkboxID);
// delete that cookie with the same ID number.
document.cookie = "todo-" + checkboxID + '=; expires=Thu, 01-Jan-1970 00:00:01 GMT;';
}
It's strange because in another function I have, this same code deletes a cookie, which then gets replaced with a small change at the end of the function.
Any ideas? Thanks!
Issue was with the path not being set. Since it's a single page app, I just added path=/; after the expiry date.