Reputation: 28114
I have a situation where for some reason a Web page might refresh while a user is filling out a form. The unwanted effect is to wipe out the data already entered by the user.
Is there a solution to have the form data persist on page refresh?
The form includes text input and selects.
Upvotes: 5
Views: 11202
Reputation: 33865
You say "I have a situation where for some reason a Web page might refresh"
, do you mean that the user might refresh the page, or is it some other script that refreshes the page? If the case is the latter, you should probably try to fix the issue that causes the refresh instead of trying to preserve the form data. If it is the former, JavaScript will probably be the solution for you.
You could listen for every keyup-event on any of the form elements. When a keyup-event is fired you serialize the form data and write it to a cookie (or a webstorage, depending on what browsers you need to support), to preserve the most up-to-date data. If the page reloads, or if the user leave the page and comes back, the cookie can be deserialized on document-ready, and you can re-populate the form with the data from the cookie. When you post the form, you make sure to also clear the cookie, to make sure the form isn't filled the next time the user loads the page.
Update
Here is a good blog post about how to use GSerializer for serialization an deserialization with JavaScript.
Upvotes: 2
Reputation: 7212
Use HTML5 web storage- it is faster and more secure than cookies. You can check out the W3Schools website for some quick and basic samples: http://www.w3schools.com/html5/html5_webstorage.asp
Upvotes: 0
Reputation: 26228
A suggested approach
As the user is filling out the form, have JavaScript running that caches the entered values in LocalStorage, a cookie, or a session variable via AJAX.
On page load, check for the presence of these entries, and populate the form with JavaScript.
On form submit, clear the entries.
Upvotes: 1