state persistence on ui - javascript

Here I am posting my problem statement.
User select option from drop down. Selected value appears on page. But, when user refresh the page then that selected value disappears from page.
I need that that value should be what I selected before refresh the page.
Is this possible using js/jquery.
Please guide me how I can achieve this!
Regards

You have several solutions to do this.
Every time the user selects an option, send a http request to the server with the selected option. When the user refreshes the page, the jsp will use the collected info to pre-select the option. A common $.get in jQuery will do the trick client-side.
Set up a cookie with the selected option. When the page is refreshed, get the cookie value and use it to pre-select the option. You don't need jQuery to do this, but it may help.
If the browser supports it, use localStorage instead of cookies. It's a client-side only solution, so the info won't be sent to the server.
Set up the hash of the URL to store the option:
location.replace("#option=" + val);
You can retrieve the value when the page is refreshed using location.hash.

You have a couple of options here:
You can set a cookie using jQuery which saves the previous state. A nice tutorial can be found here: http://www.electrictoolbox.com/jquery-cookies/
you could also encode the options in the url with a query string. Some info about that can be found on wikipedia: http://en.wikipedia.org/wiki/Query_string
Which of the two you want is up to you, cookies are the way to go if you want the settings to persist if the user leaves the page and visits another time, the query string is more useful to prevent refreshing from clearing your settings.

Using the cookie plugin (http://plugins.jquery.com/project/Cookie):
$("#MyList").change(function() {
//Set a cookie with selected value on change.
$.cookie("SelectedItem", $(this).val());
});
$(document).load(function() {
//On load, set the selected item from the cookie.
$("#MyList").val($.cookie("example"));
});

Related

How to handle browser back button using javascript?

In my application, First I need to select an option and press next button.
Then I click on browser provided back button. That option should be selected when I come back to that page.
How can we do this with javascript?
You need to use Jquery/JS Session object to store your data. In your scenario whenever you select the option just update your storage object localStorage.setItem("optionVal", "test");
so when you go next and comeback to using back button just check if the optionVal is not null and has some value if it has some value just bind it with the drop down DOM. To check/get data you need to use localStorage.getItem("lastname"); since you have not provided I can just tell you the approach. Here are some links that might help:
http://www.w3schools.com/html/html5_webstorage.asp
You can create a Wizard for this process like payment option in e-commence site
http://bootsnipp.com/snippets/featured/form-wizard-and-validation
http://formvalidation.io/examples/bootstrap-wizard/
if you send the whole scenario then may me help with complete code

reload page I lose all values in form

I have made a web form that has some fields that are manually entered, others that are a dropdown, and some calendar fields that are in javascript. My latest addition has a dropdown that is populated from a selected value of a previous dropdown. When it reloads the form, I lose all of the previously entered values and only retains the value to the one dropdown. Do I have to capture all the values, or is there a way to just populate the 2nd dropdown without reloading the form?
-.- one word. AJAX. use it.
any time you reload a form you will lose all unrecorded data period.
If you must reload the page save all the data in a cookie or something.
There's a way to save data without ajax and whithout sending anything to the server. It's called sessionStorage.
// store item
localStorage.setItem("index", "value");
// retrieve item
var data = localStorage.getItem("index");
So you just have to save the datas with sessionStorage after any action (click on a button, keydown, mouseleave…) and whe you reload the page, you just have to populate it again from the data you have stored in session!
I assume that by reloading the form you mean submitting it, which then returns a version of the page with the second dropdown populated according to the submitted first dropdown. If that's the case, you might consider having all possible values of the second dropdown hidden and then populating it with JavaScript after a selection in the first one is made. If the amount of possible values is very big or has to be computed server side (as in, you cannot know all the values initially) then you could use AJAX to submit the form and avoid reloading of the entire page.
Check your page's cache-control. This attribute tells the browser to rely on its own cache to reload pages.
This can be set as a meta tag. For example:
<meta http-equiv="Cache-control" content="public">
But a better approach (in my opinion) is through the server-side, using the header()function.
Note that some prefer to set it to no-cache when it comes to forms, in order to avoid spam and also for security reasons.

Javascript: Making divs hold state of display='block' when user clicks BACK button in browser

I have a few divs on a form that are hidden by default (style="display:none;"). When the user clicks a certain radio button, an onclick event executes and exposes the divs. The user is then taken to a review page upon form submit that shows him any errors. If there are any, he clicks the BACK button on his browser to go back to the form and correct them. Caching is enabled so that all of his form contents are there. The problem is, since the form is looking for an onclick event, all of the previously exposed divs are hidden again. Is there any way to make sure they stay exposed when the user clicks back to the form from the review page? I thought a document.ready function would do it, but no joy.
As Yair mentioned, you can use cookies. It cannot be done with pure JS. However, you can also use PHP.
Before the user is transferred to the second page, have JS scan the divs in question, and find which ones are visible. (I'm assuming they all have individual IDs). Store these IDs in a comma-delimited string, or array, and send it as a _POST or _GET to the new page.
Have PHP store it as a hidden value somewhere. You could use a hidden input, or a data-x on something ... as long as it's there.
Have JS on that page that watches for the back click, stops it, and then redirects the user to the previous page, and sends the string or array back to it. Have PHP on that page print it as a JS value, and have JS on pageload show all divs with matching IDs.
Cookies or localStorage if you aim for only modern browsers:
localStorage
Is there any way to make sure they stay exposed when the user clicks
back to the form from the review page? I thought a document.ready
function would do it, but no joy.
You can use cookies in order to manage state in a web-browser. Cookies will help you save the desired user's state.
All javascript code is reinitialized on browser reload. You cannot identify whether the user comes back through the browser.
You can use cookies or local storage to save a value when initial display happens and show/hide the div later on document.ready.

Recover page content when visiting back

I am building a small web site, and on one of the pages there is a d3.js/highchart visualization demo. The visualization is interactive, and can be modified by the user.
When the user leave this page and enter another html page by following a link in this demo page, the content of the page is not saved, and when he comes back, he has to modify the chart again. My question: is there any way to cache this demo page so that as long as the user does not close the browser page, it can be recovered?
My simplest idea is to have each client page a unique ID. So that I will save the status of the page when the user leaves, and when he comes back I can cover its content based on this ID. Then the question is how to implement this ID for client pages.
You can use History API here.
When a user changes the state of the chart, the page URL is updated with all the parameters needed for rendering the chart (via history.pushState call).
On page load you get the initial state (chart parameters) from the url and render the chart correspondingly.
A good thing with that approach is that you even can send such URL to another person, and they will see just the same customized chart.
You could also try storing the page state locally using either sessionStorage or localStorage (DOM Storage guide)
If you have two or more tabs I don't think there is a way to differentiate between then once they are closed. I would use Steve's idea about storing the ID in DB+cookie and when user come back to page I would provide them with a list of all their past modified charts based on cookie and DB query. Then they can choose which chart they want to reopen.
I can think of many ways to do something like this.
If it was me, I would simply store the users chart settings in a cookie, so when they navigate back to the page, you can simply read the cookie for the settings and use them to re-display the chart.
If you want to persists this longer, then send the settings to the server to be stored in a DB. The server can return a unique ID which is then stored in a cookie, or simple use the session cookie to associated the chart settings with a session.
An alternative which doesn't use cookies is to add chart settings to the 'back' url when you navigate away. When the user clicks to go back, the url contains the information necessary to restore the chart states. However, this doesn't work if they click the browser back button.

Only do work on the first page load, not when the user comes via back/foward

I want to do some work when the user first lands on my page (via a link or directly entering the URL). However, if the user goes off somewhere else and comes back to my page via back/forward buttons, I don't want to do the work again.
What's the best way to achieve this?
Note: The work should be done if the user hits the refresh button, forcing a page reload.
if (performance.navigation.type !== performance.navigation.TYPE_BACK_FORWARD) {
//No back or forward button.
}
Combine this with localStorage I suppose.
One possible approach is outlined below, albeit, it's not at all elegant.
embed a random nonce key in the server generated page
JS checks if this random nonce exists in cookie?
If it doesn't exist, save it in a cookie and run the script
If it exists, the page was loaded from browser memory and hence not a fresh load.
Just an idea:
browsers usually remember input-values, so they will be present when you navigate back.
You may use a input(hidden with CSS).
Onload check if the current value of the input does have a special value(this value must be generated on server-side, so it will not refresh when you use back/forward)
<script type="text/javascript">
jQuery(
function($)
{
if($('#history').val()==$('#history').data('value'))
{
alert('you did use back/forward');
}
else
{
$('#history').val($('#history').data('value'));
alert('you did not use back/forward');
}
}
);
</script>
<input style="display:none" id="history" data-value="<?php echo time();?>"/>
When the user uses back/forward, the input-value is equal to the data-value attribute(but not when the user hits F5, because then the data-value-attribute will refresh too).
Best way is to use HTML5 web storage, Use session storage. When page loas first time check if local storage variable is set and stores some data, If not then set data, if user uses next/prev button and comes back again when pageload event will get called you can detect that user been here before and its not the first page load. See this demo
http://www.amitpatil.me/demos/html5-web-storage/web_storage.html and here is the detailed article http://www.amitpatil.me/introduction-to-html5-feature-web-storage/
LocalStorage would be nice here. Works similar to cookies but only exists on the client side, Nothing is sent with the headers. Others have said the same or similar, I hope this example shows you how easy it all is to do.
So you will set the value of the variable to the identifier for the current page and reference it against the variable A) existing, and B) being set to the first page.
<script>
if( !localStorage["lastPage"] && localStorage["lastPage"] != theFirstPageIdentifier ) {
// this is the first view
localStorage["lastPage"] = currentPageIdentifier;
}
</script>
Note: localStorage is not available by older version of IE (maybe others) and cookies could be used here for a fallback. Same concept.
I feel like you need an example to show you this will work: http://rlemon.github.com/demos/12323999/page1.html view source.
I think a solution to your problem would be storing a session cookie that will remain while the current browser is open , then will expire - this is easy using jQuery Cookie Plugin
Then you can set a cookie as easily as this
$.cookie("example", "foo");
The work you talk about would be performed if cookie is not present , and ignored is cookie is present

Categories

Resources