I am soo angry right now. I lost hours and i dont know why this happens. Its a semi rant but i'll try to keep it short
My code would not work, even after refreshing it was broken
I fixed my code or so i thought because it stops working without me changing anything (you would think i am imagining this...)
I somehow decide to make a new window or tab i run my code and verifies it works.
I write more code and see everything is broken again
I write test in a new window and see my code does work
I see my code doesnt work and firebug DOES NOT HELP
I notice when i create a new tab everything works
I realize refreshing does not work and i MUST make a new tab for my code to work.
Then i knew instantly what the problem was. I modify a display:none textbox but i set the values incorrectly. I cant see it because it is hidden. Now some of you might say its my fault because when doing a refresh all of the data may be cache. But here is the kicker. I was using POST data. I posted in between of the refresh each and everytime.
Whats the point of using POST when the same data is cached and use anyways? If theres no chance for a search engine to follow a block user get link then why should i bother making anything post when security or repeat actions are not an issue? POST didnt seem to do anything.
Sounds like you're being hit by form-field-value-remembering.
When you use back and forward (but when the bfcache isn't used in browsers that have it), or in some browsers when you hit reload, the browser attempts to keep the values of each form field that were present when the page was last unloaded. This is a feature intended to allow the user to navigate and refresh forms without losing all the data they're laboriously typed into them.
So you can't rely on the value of a form field being the same at page load time as it appears it should be from the HTML source. If you have DOM state that depends on the value of a form field (such as for example a form where some of the fields are hidden or disabled depending on the value of another field), you must update that state at page load time to reflect the field values that the browser has silently dropped into place (no onchange events occur). And don't use hidden inputs to store scripting variables at all.
The exact behaviour varies across browsers. For example some browsers keep the values of hidden fields and some don't. Mozilla and WebKit put the new values in instantly as the fields are parsed into the DOM, whilst IE only does it on window.onload... and Opera, aggravatingly, does it just after window.onload, so you can only catch it by setting a 0-timeout to update state after onload. It's a nasty mess.
Related
I'm writing this to document a current (apparent) bug.
Situation:
Given a webapp where users can view and sort tabular data (it is loaded from DOM, and sortable via javascript). They can use checkboxes and a buttons to take action on what is viewed.
If you use the back button to go back to the tabular data page, then the browser fills in the states of the checkboxes. This is expected behaviour.
Complication:
If you sort the table first (an in-DOM sort using javascript) and then fill in the checkboxes and go to another page, and then use the back button to go back then browsers behave differently.
Currently Chrome (58) and Safari (10.1) reloads the form and tabular data in the original (not the js-sorted) order, but restore the inputs in the order they were clicked (ie ignoring any ids for the inputs -- just their order in the DOM at the time) -- this results in very surprising behaviour (the form at first glance seems to be what you expect, but different form elements have been restored with different data)
However Firefox (v50.0) reload the form and tabular data in the js-sorted order, and the restored inputs are correct.
I've documented this more fully at https://timdiggins.github.io/back-button-restore-sorted-inputs/
Ideally the browsers would store their input data against the input's id rather than its order in the DOM, or would cached the DOM order too.
I'll answer this myself with a workaround, but I'm hoping someone will come up with a better suggestion.
Or alternatively point out anywhere in HTML5 specs that say that form's DOM shouldn't be sortable? (ie. is it possible that Chrome and Webkit are behaving to spec here).
I've found three ways of working around this. Two which are very reliable, but each lose functionality, and one which I am in two minds about
1) Disable dynamic sorting in the initial form (obviously).
2) Disable saving form state for all of the form elements with autocomplete="off" (on every input, see https://stackoverflow.com/a/2458153/109175). Optionally could skip this for browsers (like Firefox) that have unproblematic behaviour (in my use case Firefox never used).
3) An option that occurred to me is to make sure that the order is reset to the original DOM order when form state is saved. This might mean adding a before submit handler on the form (easy enough) but in order to ensure the form is restored correctly when navigating away with a simple link <a>, this might mean adding a callback before executing links -- this wouldn't cover javascript based navigation.
4) Another option which occurs to me, is to focus on the reordering process -- either to convert it from js to a page reload or to use pushState or replaceState from the History API
Both 3 and 4 seem clever, but (for my use cases) I'm inclined to go with one of 1 or 2 and deal with the reduced functionality.
Thank you in advance to anyone who attempts to help me with this.
I have a form that I am adding checkboxes to via appendChild() - as selections for the user to chose from - based on a bunch of criteria.
When the user checks any of these boxes and then clicks the 'continue' button to post the selection to another page - and then clicks the back button - the checkboxes that were checked by the user - have now been forgotten by the browser (no longer checked).
If I use php to write the checkboxes or simply have static checkboxes - when the user checks any of these boxes and then clicks the 'continue' button to post the selection to another page - and then clicks the back button - the selected checkboxes are remembered (still checked)
My question is:
Why does the browser forget the selections the user made when I create the checkboxes with appendChild()
yet the same browser will remember the selections the user made when using static checkboxes
What is it about appendChild() that is not allowing the same browser to remember the checked selection?
[div id="mydiv"] here is where the checkboxes are going[div]
[script type="text/javascript"]
var newInput = document.createElement("INPUT");
newInput.id = "mycheckboxid";
newInput.name = "mycheckboxname";
newInput.type = "checkbox";
document.getElementById('mydiv').appendChild(newInput);
[/script]
The browser may "forget" dynamic changes to the DOM because different browsers use different strategies for caching web pages. When you hit the back button, the idea is that the browser can display its cached copy rather than re-request the page from the original web server.
It can accomplish this in (at least) two ways:
The browser caches the DOM itself of a page upon leaving it. Upon revisit (forward or back) dynamic changes will persist.
The browser caches only the original HTML of the page at load time (prior to any dynamic changes). This has the effect of losing those dynamic changes--further modification to the DOM with appendChild() or innerHTML is not recorded.
Note that some browsers additionally keep modified form data, and others do not. If your goal is 99+% compatibility across all browsers, then you have some work to do.
To work around this you need to persist the state somehow. You have a few options:
Save data about the modifications to the page to localstorage. Use a key that is generated randomly on first page load and then kept in the page, so that the state changes will only apply to that instance of the page. On page load, if this key already exists, read the change data out and re-apply the changes. Older browsers do not support local storage.
Do the prior thing with cookies. I don't recommend this, as it has the drawback of proliferating cookies. Cookies are sent and received in every request (including ajax ones), so you would be bloating the data being transmitted on every request. Old browsers would work fine with this.
Abandon your dynamic change model and make the changes occur through a post to the server. Then the page will contain the modified html when pulled from the browser's cache. You probably don't want this, but I thought I'd point it out for completeness' sake.
Save data about the modifications to the page via ajax behind the scenes to the server. This is not the same as actually round-tripping each change like the previous item. You still make changes dynamically, but you post an "advisement" file to the server. Then, on each page load, request any adjustment data from the server. This is similar to the first suggestion, but you are using the remote server as your storage. This makes extra net traffic occur on each page load, but the traffic can be minimal as it would be just about this page. It also makes extra net traffic occur that would not normally be sent (the advisement data). A clever system architecture, however, could use this information to persist a user's unsubmitted form data across computers and over time in a way that could be very handy (lets say your user does 199 out of a 200-question survey and then his power goes out--with this scheme he has a chance of painlessly continuing later exactly where he left off!).
Make your Continue button open a new browser window, preserving the original page intact.
Make your Continue button post the data without leaving the page, preserving it intact. You could do a simple lightbox-style overlay.
If the lightbox-style overlay will not work but you really have to display a new page and don't want it to be in a new window, then redesign your site to work similarly to gmail: where pages change only through javascript, and only through using #hash tags at the end of URLs to control behavior. This can be difficult but there are libraries out there that can accomplish it. (For some browsers one has to resort to polling to see if the hashtag has changed.) The basic idea is that when you click a link that points to the same page but has a tag on it such as About the browser will initiate a page load event, and will push a new context into the history forward/back stack, but will not actually load a new page. You then parse the updated URL for the hash code (which maps to some kind of command) and carry it out. Through careful choice of the proper hash codes for each link, you can hide and display the appropriate page dynamically through Javascript and it will appear as if the person is navigating around a real web site. The reason you do all this is that, because the page never loads, you not only can maintain state in Javascript, you can maintain your DOM state as well--you simply hide the page that was modified by the user, and when the back event occurs that means to visit that page again, you display it, and it is exactly how the user left it. Advantage: If your site requires Javascript to operate, then you are not taking a risk by using even more Javascript to accomplish it. Disadvantage: Completely changing the architecture of your site is a LOT of work and can be difficult to get working on older browsers. To get started with this see Unique URLs. You might try out the jQuery hashchange plugin. If your web site has wide distribution you will want to be sure to address search engine optimization and web usability issues. You may want to see this SO page on detecting back button hash changes.
Use the same strategy as in the prior point but instead of doing it with hashtags, use the new HTML5 history.pushState() and history.replaceState() methods--see Mozilla browser history.
If your goal is not 99% compatibility across 99% of the browsers in use, then please let us know what you are aiming at, as there may be a shortcut possible.
Update: added an option #8
Scripting pages doesn't stop at state management. It includes state management.
This means scripted state changes such as scripted page transitions(pages that internally navigate), content panes, popover menus , style changes and of course, form input and selections are all the responsibility of the scripter.
So, in answer to why .. it is because you did not manage the page state you scripted.
If you want your page to work as you seem to expect you can manage the page state changes you script yourself, use a js lib that manages page, or perhaps in your case form, state, or use the http(s) client/server state management and load up the session state, or in your case just the form state, at the server.
I am developing a form using Javascript for styling that will be used to submit many different things. However, the majority of the time the different things will only be slightly different so it would really benefit users if when you press the Back button on the browser, the form is exactly as you left it before you submitted the form.
Note: This already works when using a normal HTML/Javascript-less form, the question I am asking is how I can retain this functionality when using Javascript to hide/replace input fields etc.
I've tried History.js and HTML5's replaceState() but nothing seems to work. Also if it helps, this will be a private website that requires the latest browser installed so don't feel hesitant to recommend solutions only available in the latest browser releases.
Many thanks!
Update #1: Here's an image better explaining what I need.
Update #2: Okay I managed to crack it perfectly, cross-browser included. I'll post a solution tomorrow after I've had some sleep.
Okay so I went back to the drawing board and tried to figure something out using the tools I already know exist. The case with each browser (usually, haven't tested any non-major browsers) is that when you press the Back button after submitting a form, text input fields are usually populated. I wanted to see if this worked the same with hidden input fields, turns out it does!
So next I set up some Javascript events to listen out for the page load.
if($.browser.mozilla)
{
$(window).on('pageshow', pageManager.init);
}
else
{
$(pageManager.init);
}
This works for Chrome, Firefox and IE9. I haven't tested any other browsers but these are the only browsers that will be used for my private site so it's good enough for me. I'm sure you can set up your own preferred solution for your needs but this is what worked best for me.
Anyway the above code means every time the page loads, pageManager.init() will run. Here's an excerpt of the code I use to check if the Back button was pressed and it's not simply just a page refresh or a first-time visit:
if($('input[name="form_submitted"]').val() != '')
{
// back button was pressed
}
As you can see, it's as simple as checking if your hidden form field contains a value. To actually guarantee a value will be set, make sure to set on submission of your form:
$('#my-form').submit(function()
{
$('input[name="form_submitted"]').val('true');
}
It really is as simple as that. This is one of the best methods I can think of for determining if the Back button of a browser was pressed. Now, to cache all the form values for the visible fields it can be as simple as using JSON.stringify() on the fields and sticking it all in one hidden field which you decode later.
AFAIK, this is generally handled manually. That is, you use hashtags or pushState (with appropriate state object) and either on hash change or on popstate you grab the hash/state, and (re)build your DOM as needed.
(note, I combined two very different scenarios into one there, sorry. if you were only using hash changes, you wouldn't likely be using pushState, as pushState doesn't trigger onhashchange according to MDN.)
I have a bit of an issue with page formatting when I navigate away, and then hit browser back to a page.
Here is an example:
I have security questions on a form in a drop down list like so:
http://i.stack.imgur.com/ib32z.jpg
When the user selects [Type in your own question] from the drop down list, I have some jquery that animates a CSS change that pushes the form down, and makes visible a hidden field for 'custom security question'. When selected, the form looks like this:
http://i.stack.imgur.com/uVPKo.jpg
Now my dilemma is when I navigate away from this page, and then navigate back using the browsers back button, my formatting gets screwed up and looks like this:
http://i.stack.imgur.com/5Xhpi.jpg
The javascript that I have written does not trigger again on the back button so the browser doesn't know to move the form back down to accomodate the change in spacing. Is there anyway I can force the document.ready to reload or clear some kind of cache?
Thanks!
EDIT: Sorry guys, I need to reupload the images to a host and repost. Sorry for the delay.
There are basically four mechanisms for persisting state on the web:
Browser-based - the browser, if you're lucky, will save answers to form fields and re-display them when it sees an INPUT with the same name; also, some browsers will preserve some state between forward<=>back navigation
Cookie-based - pretty self-explanatory; you save a cookie with the state info, and check it later to recover the state
URL-based - navigate to a different hash of your URL, with the info you want in it (eg. "?roll_down=true")
HTML5/Local Storage - Look it up if you're interested :-)
We can basically throw 1 and 4 out, because they both rely too much on browser behavior/support, and we can't reliably rely on all browsers to handle them the way we want. That leaves #2 or #3.
Cookies allow you to save more info (as much as a cookie holds, ie. about 4k). URLs allow less info, but they have the added benefit of bookmark-ability; if the user saves the URL as a bookmark (or as a link they send a friend, or whatever), the state still gets preserved.
So, take your pick of the above, decide on how to persist your "my form is rolled down" state ... and then comes the part that (I think) you're really interested in: how do you check this state and fix things when the user clicks "back"?
That part I humbly defer to another SO post, which has already answered it:
Is there a way to catch the back button event in javascript?
I've been trying to find a workaround to the back button bug in Safari/Chrome (browser putting bogus data in fields where they don't belong). I haven't had any luck, and it seems like there should be a good solution to this by now (I see posts about this going back to 2009, but no good solution).
In this example: http://jsfiddle.net/eGutT/13/
you can see that everything is fine on the initial page load. However, after clicking the link, then clicking the back button on the browser, values are propagated the the wrong fields. Please use Safari or Chrome to test. It works fine on Firefox.
This is a very serious problem, especially when:
User goes hits the back button, and this bug occurs
User doesn't notice the bogus data
User makes some unrelated change to the form (in a different unaffected field)
User submits form
Now you are left with a situation where the bogus data is committed to the database!!
BTW, this problem may be related to jQuery, since if you uncomment this line in the example:
updateRowNums(); // IF YOU COMMENT OUT THIS LINE...
no extra/bogus data gets introduced.
Thanks,
Galen
Are you talking about the 0, 1, and 2? Because your function updateRowNums is automatically forcing those values. If you want to maintain that first column, you could change updateRowNums to something like this:
if (!$('#some_id').val()) { $('#some_id').val(x); }
(Obviously it's not the most efficient code, but it resets the field if no value is present.)
However, if that isn't what you're talking about, then I couldn't reproduce your problem. I'm using Chrome 9.0.597.83, and it saved all the right data in all the right places.