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).
Related
I'm using TaffyDB to have a local/offline database
but unfortunately - after refreshing the browser tab - it loses the data
example:
I have this initial variable
var clist = TAFFY();
onclick event on button - it execute this statement
clist.insert({"123" , count:count , color:color , size:size});
after clicking it - and reload the browser tab , I execute this statement
alert(clist({PID : "123"}).count());//output 0
however the previous statement should output 1
but unfortunately - after refreshing the browser tab - it loses the data
Well, yeah, that's how TaffyDB works.
however the previous statement should output 1
No, it shouldn't.
TaffyDB is in-memory only. As soon as the context for your script is torn down, such as on a page reload, it's gone. If you want to persist it, you have to do that yourself.
The easiest thing to do is serialize the entire dataset as JSON and shove it in localstorage, provided it's small enough to fit there.
As per taffydb documentation, to persist data into localStorage, you can use db.store()
let db = TAFFY()
db.store('mydb')
This single function will both store the current data in-memory and retrieve previously stored data. So, if you call store at the beginning of your script, then on a window refresh, the stored data will be loaded.
BEWARE: However, the saving routine for db.store() is called as a non-blocking process... so if you wish to immediately retrieve data that you stored using some other call on localStorage, it will likely not be there. The best practice for store() is thus to call it on window load and then whenever you wish to save your existing data.
Scenario:
Let's say we have and app which works like:
Header
Content
footer
Header and Footer are statics and content is a div which is called via ajax to load an specific view.
So basically, our first view is login, after calling a login controlling, we get a list and move across the app w/o changing the link structure cause the ajax div content calling.
Problem:
When we refresh, we go back to the login page instead of the main view, which displays all the options which comes with the login controller answer. I'm trying to keep those options into a global variable, however after refreshing, all data is erased and there is not way I can go back to the main view even if session is alive (by session cookie), I only can back if I send the user and pw again, which I cannot. Eventually, storing the user and pw into cookies is not an option.
Any advise to solve this issue?
You can use DOM Storage to store the value of your global variables between reloads.
DOM Storage is a client side key/value storage.
localStorage.setItem('key', value);
value = localStorage.getItem('key');
There are two variants:
sessionStorage, this will store the value for the time of the users session
localStorage, this will keep the data between sessions
If you have to support ancient browsers you can use cookies to store values between reloads.
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.
i have a code here but i don't know how to pass it to the other page... basically it is inside a function so before the code there is a function but i think there is no need to worry about that what i need is to change the "alert" so some kind of variable where i can grab the value and output it, and also i would like to ask because the data in that function is an array is it correct if i write it like this? var x=new Array($(this).attr('fill')); and if it is correct how will i grab the array data into the other page?
$('text').each(function(){
alert($(this).attr('fill'));
i have a working link here but in this one i still need to change the alert into a variable i can call
It's not entirely clear what you're asking, but to get data from one page to the next, you have the following options:
You can store the data on your server and each page can get the data from the server or have the server put the data into each page when the page is constructed.
You can write the data to HTML5 local storage in the browser and each page (on the same domain) can retrieve the data from HTML5 local storage.
You can write the data to a cookie in the browser and each page (on the same domain) can retrieve the data from the cookie.
You can pass data to the next page via the query string in the URL.
Javascript variables and properties of DOM objects live only for the duration of the current page. When you go to another page, the entire javascript state is thrown away and does not survive on the next page (it is built again from scratch on the next page). This is why you must store the data somewhere and then each page can retrieve the data.
Setting global variables in my js file doesn't seem to work. How can I set rails session variables from JavaScript?
I'd like a solution that doesn't use jQuery.
Edit: The solution is to use an HTML form containing hidden fields.
Global variables only live for the duration of a page view. Once the page is rerendered, they are reset to what their default values are.
If you need to keep the values, you need to use cookies or local storage. Other option is to submit them to the server with Ajax and have the server remember them and set the values when the page is rendered.