Javascript save settings to one or more cookies? - javascript

On a blog I am working on, I use a cookie to save a user preference on which side of the layout that the sidebar should show, so I have a cookie something like this...
name: sidebar_switcher
value: right or left
No wI just built a Modal/screen overlay DIV that shows on users first visit, I made it set a DIV once this Modal window is hidden/closed so that I don't nag the user on every visit with it. SO I now have another cookie being saved like this...
name: subscribe
value: yes or no
So my question, since each Cookie is a new HTTP request as far as I know, should I instead be storing these values into 1 cookie? If that is the case, then should I do it as a JSON string?
Thanks for advice

You could store it as one cookie, or you could use localStorage() with a fallback on cookies.
That way, your users with modern browsers don't need to parse any cookies around.

Related

how to pop up a Notice Span when user just log in (but not just refresh to the home page)?

I do not know how to detect it is the first time that user login the web.
I thought i should write a pop-up span on the jsp that user firstly saw when he login.but the issue is then he refresh the page,the notic will show again,that is ridiculous.
I need detect if it is first login means to detect if the user JUST LOGIN or NOT REFRESH the page
how and where shall I detect if it is the first time user login ? and then i can make mind if the notice span pop up.
and I think it should use cookies or session,but which one should i use?
Maintain a field in database table that check if it is first login than show a popup and after that change the value of that field so that Popup do not appear next time.
Ex:
if($data['first_login'] == 1)
{
// show popup
}
If you want to show it only to the new user (the time user registers) you can use a table column in database where you can use it to check if the user if logging in for the first time (e.g firtsLogin the column name = 1 ). If he is logging in for the first time you show the pop-up and change the value of the field to 0.
Otherwise if you want to show to users that are logged in to a specific device for the first time you should use cookies.
I suppose that you want to detect the user logging in to your web-site the first time. There are multiple ways that you can do it depending on your desire to spend additional time writing the code, the location of your logging-in logic (client or server side), security that you want to have while proving your users with login functionality. In all cases - you would have to store the data whether the user has logged in for the first time. I think you are seeking a fast solution that will work without a big care for privacy or security as working with client-side cookies isn't the safest way to store data. The alternatives to cookies are web tokens, url query string, server-side sessions and data-base (RDBMS) storage.
Storing and retrieving the data on the client-side using COOKIES. They are the pieces stored in the user's web browser. Cookies were created to help servers remember the data about the user next time he enters the web-site. The most common usages are: to store location (if accepted by user), web-site locale (language in which the user was browsing the site), products added to cart, etc. Following that approach you can create cookie after the user has logged in to your web-site as follows:
This should be run by your JavaScript.
document.cookie = "firstLogin=true";
After having done that, you would have to add JavaScript logic that will hook-up to user's/client's COOKIE data and read up whether he has logged in the first time before.
This would probably look like a simple JavaScript cookie look-up.
var cookieData = document.cookie;
This will return all of your user's cookies that has been previously stored when he visited your web-site. It will return it as a string concatenated with "; ". If we had previously stored only one cookie, we would get firstLogin=true;
In case if you have multiple cookies set before, you would have to parse the cookie string and extract the data either imperatively by plain procedural JavaScript code or by writing the function which will be able to do that repeatedly. Detailed examples of writing such functions could be found here.

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.

Detect if site visit is new with js

I would like to check if a user who opens my website is new (type in url OR redirect through google) and then display a message.
But when the user browse through the site (subpages like about and so on) this message is not displayed.
But when the user closes the browser and visits (maybe a few mintues later) the website again, the message should be displayed again.
How can I implement something like this in JavaScript?
You could use cookies, localStorage, sessionStorage or the referrer info. Note that all of them have their own pros and cons and there is no 100% reliable way of detecting new visitors.
Using the firstImpression.js library that Nadav S mentioned is probably the easiest way.
To get the message to show up for users closing and reopening the site:
unset your cookie / localStorage data on unload or
use a referrer info or sessionStorage based solution
See these MDN resources for more:
cookie
localStorage
sessionStorage
referrer
Slightly relevant as well: http://www.cookielaw.org/faq/
From the MDN:
Returns the URI of the page that linked to this page.
string = document.referrer;
The value is an empty string if the user navigated to the page
directly (not through a link, but, for example, via a bookmark). Since
this property returns only a string, it does not give you DOM access
to the referring page.
This means:
if (!document.referrer) {
//Direct access
} else {
var referer = document.referrer;
//Request comes from referer
}
If you want to save this state, you need to take a look at cookies.
Quite easily, you want session storage
var hasVisited = sessionStorage.getItem('washere');
if ( ! hasVisited ) {
// do stuff
alert('Welcome, stranger !');
sessionStorage.setItem('washere', true);
}
You can implement this by using cookies.
When the visitor first come to your page, you check if your cookie exist, if not show the message to them and then create the cookie for future pages.
Using cookies is probably your best bet. They are super simple to use too. Just write
if(document.cookie = "HasVisited=true"){
//whatever you want it to do if they have visited
}
else {
document.cookie = "HasVisited=true"
//that just saves to their browser that they have for future reference
}

js function to go back in browser history to last browsed page of specific domain?

I need the js function to go back in history to the last pages used in a specific domain.
reason: I send people to a subdomain to see specific content-galleries (gallery.mydomain.xyz/#1etc). I need them to return to the last page where they left of from the specific tld (mydomain.xyz/pageX) after having clicked through a number of images/videos there at subdomain...
is this possible? any ideas?
thx!
It's not possible using the built-in browser history, no, because your access to that from JavaScript is close to non-existent.
What you can do instead is save the location you want to take them back to in, say, session storage (use local storage instead if this is in a different window), and then link back to that page.
More about session storage / local storage in the web storage spec, but the short version is that it stores strings in a storage area specific to your origin, so for instance:
localStorage.setItem("last-location", "foo");
...stores "foo" in local storage for your origin, with the key "last-location". You can then use getItem to get it later when you need it:
var lastLocation = localStorage.getItem("last-location");
you could use a simple get/post variable to tell where the user is coming from and store that in a session variable for later use when the user is to be returned. As far as I know you cant access the users browsing history from the browsing client with Javascript as its a violation of the sandbox design but that may have changed recently
thx both of you for the quick answer!
... I kind of see, not being a versatile coder myself. but I get the problem involved. and see session-storage is where I want to look at then...
I will have to make this a coding job given my non-skills here :-}
but now I know what to ask for. thx again.

How to retain textbox values after navigating to other page?

I have a page(say register page) with text boxes in it. After entering values in them, if I navigate to other to page by using back and forward buttons in the browser and come back to the register page again. I want the entered text box values to be shown. Is there any way to do that. Hope somebody could help. Thanks in advance...
saving to local storage is a bit dangerous, because anyone can go to console and type:
window.localStorage to see the saved values, for ALL USERS of the domain.
for example, on this page of SO right now, the localstorage contains this :
Storage {login-prefs: "{"provider":"google","oauth_version":"","oauth_server":"","username":""}", se:fkey: "c6f10e10979159fee3220954ec846d68,1387300621", wb:isparticipating: "{"1106914":{"t":1387805621703,"v":false}}"}
assuming that the textbox values do not contain personal information,
you will still need to address issue of multiple users on same machine.
one solution will be to use the user ID as a key, the value as a json representation of textboxId : value
example:
on window.befreunload event, strore all the textbox values under a key containing user ID:
localStorage.setItem( 'user_123_form-values' , JSON.stringify( [{ txbox1: 'some text' }, { txbox2: 'some other text' }]) );
to get values:
JSON.parse(localStorage['user_123_form-values'])
here is a fiddle to demonstrate the local storage approach, though if the data needs to be secure,
you will need to use cookies:
http://jsfiddle.net/LLyB6/2/
JS variables never have been persistent, but there are two ways around this:
1.Cookies
2.Storage
Cookies are supported in all but the most ancient browsers, but they can be very unwieldly and difficult to use. On top of that, your browser sends cookies to the server with every pageload, so if it's only used by JavaScript then it's very inefficient.
Instead, you should probably look at the Storage option.
Saving an item is as simple as localStorage.itemname = value; Reading is as easy as localStorage.itemname, and deleting is as literal as delete localStorage.itemname
These values are saved across pageloads, but not sent to the server.
from:
Javascript global variable does not persist when navigate to another page (which also uses same js file)
What you are looking for is done using session / cookie / Appending query string:
Check this answer: PHP Pass variable to next page

Categories

Resources