Use javascript to remember what choices the user made on previous pages? - javascript

I have some pages, on the last page I need to know what choices a user made on the two last pages.
Like this:
a.html
User has three choices here that takes him/her to different urls. I need to somehow save this choice and use it later.
Example:
<script>globalVariable1="firstchoice"</script>
b.html
This is one of three choices page and here the User have 3-4 new choices that takes him/her to different urls. I also need to save this choice somehow for later use.
Example:
<script>globalVariable2="thirdchoice"</script>
c.html
This is the page where I need to know what choices the user has made earlier. To be able to link back to those exact pages if the user wants to go back in my breadcrumb-solution.
Example:
<script>
if(globalVariable1 == "firstchoice"){
//do this
}
if(globalVariable2 == "thirdchoice"){
//do this
}
</script>
Can I do this with some global variables in javascript or how can I solve this?
Thanks

You can use localStorage. A browser API that persists key/value pairs even if you navigate between pages, reload the page or close and reopen the browser.
//setting a value
localStorage["foo"] = "bar";
//getting a value
var x = localStorage["foo"];
Using sessionStorage will also work.
//setting a value
sessionStorage["foo"] = "bar";
//getting a value
var x = sessionStorage["foo"];
Wikipedias Web Storage article describes the difference between localStorage and sessionStorage as:
Data placed in local storage is per domain (it's available to all scripts from the domain that originally stored the data) and persists after the browser is closed. Session storage is per-page-per-window and is limited to the lifetime of the window. Session storage is intended to allow separate instances of the same web application to run in different windows without interfering with each other, a use case that's not well supported by cookies.

You will have to store cookies to track the user's state. Try cookie.js. It has a really simple key-value interface that you can read about on its GitHub page.

Web pages are stateless, so you cannot share global JavaScript variables between pages.
However you can set global variables for your page and containing modules by using the value of the cookie.
Your cookies will be available on all pages of your domain for the current browser.
Example:
//Page 1: Set cookie depending on user choice
$.cookie("choice1", ValueOfChoice1);
//Page 2: Get previous user choice
globalVariable1 = $.choice1("example");
You can read Setting cookies with jQuery if you want more details about how to use cookies.

you can use localStorage or sessionStorage.

Another choice if you're using some server-side language like PHP or Asp.Net is to sore those values in the user's session on the server.

Related

Why can't I use globals in separate html and js files?

I have two html files: index.html and lobby.html. In main.js, which I load in index.html, lobby.html is loaded using window.location.href. I have tried every way of defining globals in main.js (namespaces such as: var Global = {}; Global.variableName = 0; ... Global.variableName = whatever;, simply defining variables out of function scopes: var myGlobal; and even using window. to define and use globals: window.myGlobal = 0; ... window.myGlobal = whatever;). No matter any of these approaches, every time I try to access these "globals" in a separate script in lobby.html, it always throws an undefined error. How does this make any sense?
The answer to your first question, Why can't I ...?, is that you start a new session whenever you load a page. So, any of the Javascript variables from the previous session are gone.
The other (implied) question, How can I keep the value of Javascript variables across sessions? is either to use cookies in Javascript (MDN) or append request variables to the end of your URL then process them when the new page loads: GET (SO)
When a new page is loaded, you are essentially starting a new session as explained by others here and hence the data will be reset. For retaining some data across pages, you could use HTML5 Web storage - Session storage or Local storage as per your business needs.
MDN source
The two mechanisms within Web Storage are as follows:
sessionStorage maintains a separate storage area for each given origin that's available for the duration of the page session (as long
as the browser is open, including page reloads and restores).
localStorage does the same thing, but persists even when the browser is closed and reopened.
W3Schools
HTML local storage provides two objects for storing data on the client:
~ window.localStorage - stores data with no expiration date
~ window.sessionStorage - stores data for one session (data is lost when the browser tab is closed)

Sharing username and password to the next HTML page

I need to share the username and password information to the right next HTML page after succeeding the login. Because the items in the second HTML page will appear according to the user identity and privilege.
I tried sharing the same js file between the 2 HTML pages. The first set the variables and the second get them, but they don't get passed. How do I do it? javascript? jquery? on the server side??
Thanks in advance :)
It can be done in many ways, but as the first language you mentioned is javascript, I will show you in it. So saving data across pages there are variable called session variable and the process of saving/retrieving them is called session management. There are many ways for session management, one most common way is using cookie. You can save the values in cookie, like this:
setCookie("key", "value", expire_time(integer));
And now on next page to get this value you can use:
var val = getCookie("key");
Hope this helps.
Username and password is a sensitive information you have to share it form Server side in these ways:
Use post method to share this information.
Set session on first page For user type and retrieve on very next page.
As your question says second page will appear according to the user identity and privilege. You can set user identity (User Type) and its privileges.

localStorage sign up users how to redirect without losing data

I have a problem with a sign up form. Every time a user creates an account I use localStorage to save the form values. But if after the submit button the user redirects to another page it saves only the last user data who signed up. If after sign up I dont redirect the user to another page I can have more than one users. What can I do to save more users (using localStorage)
the code is:
var passwords=[];
var people= [];
function submitSignUp(){
var usr = signupform.elements["username"].value;
var pass = signupform.elements["password"].value;
people.push(usr);
passwords.push(pass);
localStorage.setItem( 'peoplenames', JSON.stringify(people));
localStorage.setItem('urpasswords',JSON.stringify(passwords));
window.location.href="accountCreated.html";
}
also I use a input type button and not submit because I have the same problem with the submit input. What can I do? Thanks.
Demo
So here is the jsfiddle that should work for you.
some key things are the following.
if(localStorage.getItem('users') != null){
users = JSON.parse(localStorage.getItem('users'));
}
this code checks if the users string has been set for the current page. If users has not been set on local storage is skips this step entirely.
as for processing information from page to page, you will need to do 1 of 3 things.
Send all your calls via ajax. JQuery Get would allow you to stay on the current page while loading content from other pages. You would use the get or post like an IFrame
Navigate through your site using only get methods. Javascript wasn't meant for this, and this doesn't give you much control over the initial state of a webpage.
If you don't want to use Javascript for the rest of your life, or have personal information that shouldn't be held on a local machine. IE: passwords. Use a Server Scripting Language.
In the end it is up to you to decide what to do, but my recommendation would be to use Server Scripting Language and some sort of Database. These are web standards and are marketable skills.

Using Global Variables between multiple functions in JQuery?

I want to dynamically load an image using jQuery like this:
main.js
var slidersrc=""; //try to define global variable - not sure if this is correct
jQuery(document).ready(function() {
jQuery("#sliderimg").attr('src', slidersrc);
});
jQuery("#selection1").click(function() {
slidersrc='wp-content/themes/*****/slide1.png';
});
So the first time user access my website, the slider is empty. After user clicks on one of the selection areas, I set the global variable value. Then if user continues to navigate at my website to different pages, the user should be shown a slider image as a result of his selection.
However, this doesn't appear to work.
Am I correctly using the global variable in jQuery? Or is there a better way to save the user selection value in client side?
thanks!
Global variables do NOT survive from one page to the next. Each page starts an entirely new javascript context (all new global variables, functions, etc...).
If you want to save state from one page to the next, your options are:
Put the data in a cookie which you can read from each successive page when that page loads.
Put the data in a browser local storage which you can read with javascript from each successive page when that page loads (recommended option).
Store the data on the server and embed it in each page as it is served from the server.
You can read about how to read and write from browser LocalStorage here and here.
If you're planning on changing the slider image each time the user clicks, then perhaps you want to save an index into an image array in local storage. When the page loads, you read the current index from localStorage (or supply a default value if no value exists in local storage), then write back the current value to localStorage for the next page. If the user takes some action that causes the index to update to a new value, then you update your page and then write that new index into localStorage so the next page can read it from there and so on.
LocalStorage is a similar concept to cookies, but it's a bit easier to manage and more efficient (the data is not sent to the server with every page request).

Storing JavasScript settings locally

With HTML5 and local storage, can JavaScript be used to save the state of a web page?
For example, some sites have increase font size buttons that are most likely controlled with JS. How can the property be saved so that on a refresh the size stays the same? Or is this done without JS?
Your best bet is probably to use localStorage, unless you do not want the settings to persist upon new sessions (you would use sessionStorage in that case). If you have multiple settings, you can store a serialized representation of your settings.
E.g.
var settings = {
fontSize: '11px',
otherConfig: 'test'
};
localStorage.setItem('settings', JSON.stringify(settings));
//then you can retrieve it
settings = JSON.parse(localStorage.getItem('settings'));
console.log(settings.fontSize); //11px
Note that if you want the settings to persist when users connects from multiple computers, you will have to use some server-side support.
Yes, it is done with Javascript. You can use
Cookies
Sessionstorage
This is a global object (sessionStorage) that maintains a storage area that's available for the duration of the page session. A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window will cause a new session to be initiated.
Localstorage
localStorage is the same as sessionStorage with same same-origin rules applied but it is persistent.
The better/easier ones are sessionStorage and localStorage. The problem is that they aren't supported by old browsers.
Instead, dealing with cookies can be a nightmare, but they work on old browsers too.
Yes can save state to localStorage.
assume you have an object :
var settingsObj={
pageClass:'bigFont',
widgetSortOrder : [1,5,3,7]
}
You could save that whole object to one local storage key by stringifying the object. When page loads you would see if that key exists in localStorage and have your javascript do whatever it neds to with those settings
To stringify and store:
localStorage.setItem('mySettings', JSON.stringify(settingsObj) );
To retrieve from storage and convert to js object
var settings=JSON.parse(localStorage.getItem('mySettings'));

Categories