keep global variables alive after resfresh, javascript - javascript

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.

Related

How to maintain the page state when browser back button is clicked?

I have a page with Client side paggination and Filtration. The page lists around 200-300 prouducts.
The page contains some filters like Category,Manufacturer and Weight.
Clicking upon any of the page number or filter, I am manupulating the page content on client side using Jquery.
Everything is working fine till this step. Now there is a usecase where I am facing problem.
Lets say a user comes to our product listing page and click on some of the filters and gets a list of products.
Now he clicks on a particular product , which redirects him to the product page to view the details of the product.
But now when the user clicks on the back button , the user gets the page with the intial state without any filter selected.
Is there any way user will get the page with the filters previously selected on clicking the back button?
You can use some of the following to store data across multiple pages.
Store data in cookies.
Store data in local storage.
Store data in the session on the server.
Make the data part of your URL (use hash or query string for the filter parameters). Note that changing query string causes page reload.
If using cookies, local storage, or hash, you'll need to add JavaScript code to your page that loads and applies the stored data on page load.
There is a number of ways to do this:
If you are dealing with html5 history and a single-page application, then you are not reloading the page. But based on your question, I assume this is not what you are dealing with.
Store something in the URL. For an example of this, look at the filters on TotalHockey, e.g. http://www.totalhockey.com/Search.aspx?category_2=Sticks%2fComposite%20Sticks&chan_id=1&div_main_desc=Intermediate&category_1=Sticks so when you go backwards, the URL contains the entire state.
Use localstorage, if you have a browser that supports it.
use cookies with the $.cookie API
Store it on the session in the server.
You can store the Search Filter Data in session just after submitting on the filter input and on each ajax request (Loading your product listing), you can check the search filter inputs stored in the session and show the data according to them. If search session is empty then show whole listing.
You can also store the full ajax request URL (if GET method is used) in the session after searching the record and hit that particular URL again after coming back from product detail page.

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).

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

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.

How to keep HTML Element on Browser Location Change

Is there a way when Page change location to keep some HTML Element's.
Like a div that will not be re-rendered but keep it's state.
You can find and example like that at Facebook Chat ,you can see that the Chat window does not change it's location or InnerHtml when you navigate to another page.
PS : I have no clue where to start so any documentation would be appreciated.And it would be nice if solution would be XHTML not HTML5
I don't know exactly how facebook chat works, but I do know all chat messages are stored in a database, so you can access them later via messages.
My assumption would be that a Session variable is set letting facebook's UI know what chats you have open, or perhaps its stored in the database as well. In either case, you'd have to use some outside script in order to do this. For sake of ease lets say you'll use PHP, and you'll store the data in a SESSION variable.
/* Storing the variable */
$users = array('user123', 'user456', 'user789');
$_SESSION['chat_windows_open'] = $users;
/* Retrieving the values */
foreach($_SESSION['chat_windows_open'] as $chat) {
/* Use $chat to get the username, query the DB for
the message content, and echo it in whatever form you
wish. */
}
When window.location changes, the page is automaticaly, entirely re-rendered. So, from this point of view, the answer is no. However, this effect can be obtained by using AJAX. Use ajax to make requests to the server while the page does not reload or changes location(window.location is always the same). Here's a good link to start with AJAX:
http://www.w3schools.com/ajax/default.asp
If you still want the page to change it's location, after you've made your ajax request and updated the content on the page, you can use javascript's history.pushState function. However you will have to find a way to make it cross browser(aka. make it work in IE).

What is a non intrusive history back button or alternative if Javascript is disabled?

If JavaScript is disabled what's a way of linking to the previous document in the session history?
Can PHP be used to simply link to the REFERRER or is there a better alternative?
Edit: Further to this, can previous post variables be retained?
You're really mixing the idea of previous document in client session history vs. server session history.
Since Javascript is client-side, executing a history.back() renders the control to the browser, which then decides which page was last in the history (keeping in mind that the last page may not be a page within your domain). When you're using server-side PHP, the HTTP header referrer is whatever the browser supplied to you. If your server-side URI wasn't called as a result of an explicit click on a link, form GET/POST, etc. , your script probably won't get a referrer header value.
If you only want to capture the referrer within your site's domain, you can start maintaining a breadcrumb trail server-side (in the user's session). eg: $_SESSION['breadcrumbs'] = array( 'page1', 'page2', ... )
POST variables can be persisted in the SESSION too though I've never seen a good reason to do so. If you're trying to return an error message for a form and expect to get back the POST, you shouldn't be saving the state of the original POST.

Categories