Save controller state on page refresh - javascript

I'm trying to implement a gmail like save message as draft functionality in my form.
Use Case: There is one form with certain fields which includes some text box, some image uploads, etc. My problem is how can I retain the values of these if these have been filled by user on a page refresh. Remember page is not yet submitted by user. If it has been submitted then I could have retrieved the values from server but how can I store values in input box now in case no submit button is clicked.
Should there be some api which will save the values regularly or can there be some api which can be invoked only when user is about to close the page or refresh it ?
I have no idea about this and would appreciate any pointers in this.
Update:
Based on the suggestions, I tried to explore some tutorials/blogs which can show the preoper design and implementation for using local storage. I found following good links:
http://yeoman.io/codelab/local-storage.html
https://domantasjovaisas.wordpress.com/2014/09/05/angularjs-saving-global-variable-in-localstorage/
Few doubts:
It seems we can store a JSON object in local storage but how can I store a given object for a given user.
Use Case: A user can create multiple messages. I just want to keep the last message which was not saved neither sent. How can I design this so that storage works fine ? For a given userId I want to keep some data in local storage. Is it safe to store a db Id in local storage ?
Please suggest

I suggest using a library that abstracts over localStorage and defers to cookies if you are looking to support older browsers. Use JSON.stringify and pass it to your storage service. You can also append usernames to the key if you are likely to have multiple users on one machine. It would be good practice anyways.
Examples include:
https://github.com/grevory/angular-local-storage
http://ngmodules.org/modules/ngStorage
You can hook into ng-change, watches, event listeners or use a timer as someone else suggested.
UPDATE: You can find a trivial implementation here, http://scionsoftware.com/Blog/saving-form-state-with-angular-js/
If you're looking to do it for only one string value as you implied, simply remove the JSON.parse and JSON.stringify pieces from the javascript.

Related

Remember changes made in css

I have a question about jquery, I want the user to be able to change the color of his/her profile. How could I manage to let the website "remember" that the changes were made?
$(document).ready(function() {
$('#color2').click(function() {
$('#color').css("border-color", "#3498db").css("color", "#3498db");
$('.navbar-default').css("background-color", "#3498db");
});
});
this is what I have to make the change
If it's a simple application, you might want to use the local storage of the browser.
localStorage.setItem('color', '#123456');
localStorage.getItem('color');
localStorage.clear();
Note that it's not bound to the users' profiles but scoped to the browser in use. If they go with another browser or use a different machine, the setting isn't known, which can create a weird issue when they jump between settings without understanding why.
In such case, you're better off seding the value picked to the server and storying it there. That requires you to managed it in the server-end code, which might be pulling a nuke to kill a fly.
This could be done via cookie or save it on your database using php not jquery, because jquery is used for user interaction or interface but you can use it to retrieve data using ajax.

HTML hidden input shouldn't be editable

I just discovered a bug which I couldn't find any solution of, I would like your advise on that. Issue is there are a few hidden input types, which are there to store ID's of already saved data such as per person id if it is already saved etc. etc.
I just tried and change the value of that hidden variable manually, using google chrome and submit the form and surprisingly i did not get the id that should be there but instead i received the Id that I changed. for instance there was an value of 22 I change it 263 I received 263, whereas I should have be receiving 22. I want that 22 to come not that 263.
Its hard to explain I know but I have tried my level best to convey my issue please help and advise my on that how should I store some hidden value that are un-editable.
Any Idea?
Rule of Web Development #1: Never trust the client
Rule of Web Development #2: Never trust the client
Rule of Web Development #3: You can't make the client trustworthy
If the user shouldn't be able to edit it, never give it to them.
As others have said, there are a few ways to handle the situation. The most common is to use a SESSION variable on the server, available almost everywhere.
Store the "secret" values on the SESSION. They will be available when the user posts back.
You cannot control what data users put in HTTP requests to your server.
Instead, use authentication and authorization, on the server, when the request is received, to make sure that the user is allowed to submit the values they submit.
If you're wanting to keep track of data from one page to another I would use sessions. This is data that is tracked on the server.
//page one.php
$_SESSION['id'] = 22;
//page two.php
echo $_SESSION['id']; //22
This is a basic functionality of how browsers work - essentially someone could POST data pretending to be your form with whatever values they wanted in the fields - or even add extra fields.
If it's a problem consider moving that data from hidden fields to session variables.
If it's important for your hidden fields to be secure, don't contain them on the client-side. Client side variables are pretty easy to modify.
You should probably store them in your session, so they're not outputted to the client. If they're required on the page, use AJAX to grab them instead.
It kinda depends on the domain of your application, if it's in-house software then I wouldn't worry about it particularly.
It does not look like a bug.
What scares you about this? These fields are not going to be accessed and changed by your visitors. If you're afraid someone is going to hack the http request of your visitor and change his order (for example), then https connection should help.

Store cookies as a user progresses through a form

I am trying to figure out the best way to go about this. I have a form with a bunch of input fields eg. first name, last name, address, etc. My question is what is the best method to go about storing cookies as the user is entering data and progressing through the form.
My first thoughts were to use the onchange event and call a create cookie function, but my worry is that if the user were to change a field twice would two cookies be made even though they were passed in the same name? Or would the first one with the same name be overridden?
Thank you
Do you really need to create a separate cookie for every form field? You could have a method that serializes the whole form, and stores all the data in a cookie.
With jQuery, you can use the .serialize() method:
http://api.jquery.com/serialize/
And you can also use the jquery-cookie for storing the data in the cookie:
https://github.com/carhartl/jquery-cookie
Depending on the usage you're looking for a cookie may not be what you're looking for. Let us know what you want to do and we'll help you get your solution. In any case:
You can create and destroy cookies with javascript: http://www.w3schools.com/js/js_cookies.asp
To update a cookie you would delete the cookie and recreate it.
However I would posit that you probably don't need cookies. You could store all your data in hidden fields and send them on form submission. Or send them to the server with ajax and have the server store them in the session.
Cookies are stored on the user's local machine as key-value pairs, with an optional expiration period (the amount of time before the cookie is no longer "valid").
Depending on your key naming choice, it will persist as long as it hasn't had its value changed or has been explicitly cleared.
You could do this with an onchange event, and just use the form field ID as the key and the entered text as the value.
Though it might be a better idea to store the entire form as a cookie using jQuery.
Depending on your browser-compatibility requirements, you might look into something like local storage instead of setting and resetting cookies
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage
Or, as others have suggested, serialize the full form in a single cookie.
Through a little experimentation, creating a cookie with simply document.cookie and a name= value pair and then updating the cookie using the same name and a different value does not create two cookies, it does indeed just update the first one. So my onchange idea is seemingly working fine. Through the experience I have also found that local document.cookies do not seem to work on google chrome, but function just fine in mozilla firefox.

javascript to save history

I have a html form which are paginated.I need javascipt that can save the history of value of input, user click next pages and when return to previous page can see what was wrote.
You have several options. You can for example use local storage.
But since that is not supported in older browsers, you can fall back to a cookie mechanism for example. Check out jstorage.info for a library that handles this fallback behaviour for you.
Use Cookies method in javascript to store text box value.
Keep a JavaScript variables value after a page refresh? this page gives more information about cookies.

Shall I use javascript for page submission?

I am working on a big site, and in the site there is a search module. Searching is done by using a a lot of user submitted values, so in pagination I must pass all these data to the next page, appending the values to url make the url very big.
Sso how can I solve this issue? I am planning to use a javascript based page submission (POST) with all the values in hidden fields to the next page the read all the values from the next page.
Will it cause any problems? Or should I use database to keep the search criterias?
I would create a server side object, possibly with a database backend which is updated by the different pages.
It is at my opinion the most clear and easy solution. Giving parameters from page to page, either by post or javascript or cookie will work too but it's more of a quirk in my experience.
Also if a search query is so complex that it needs multiple pages to create it, it might be helpfull for the user to have all the data stored on the server so he can change it more easily by switching back and forth between the different pages.
I would store all the search criterias in some kind of session-store on the server when the initial search is being triggered.
For pagination I would retrieve the criterias from the session-store and then just show the appropriate results. Also I would append some kind of key to the pagination links (so this would be the only hidden post-field) under which the search criterieas can be found.
Even though the session is per user, you might have several search windows open within the same session, and you don't want to mess them up with the pagination.
In order to make a reliable search with pagination, we need to do a bit more than normal.
We need to handle the following cases.
Once search is done, user may choose to do browser back and forward. Here, if you are doing form submission on every page, it would be an overload. Also, if user presses browser refresh button, it will unnecessarily warn him that data is being submitted.
Searching on a large database with lots of criteria is costly. Hence, optimization is important.
So you should NOT do the following:
Submit data on every page change
Not store data in cookie. (This is not secure and not even reliable.)
For large database with complex query, cache the result in session.
In case, you need very up-to-date and real-time result, ignore point (3) and try doing partial search for every page.
Thus, for your case, you can do the following:
When user searches first time, make the form POST data to a search page.
This search page will store the search query in session and generate a unique id for it.
Now render the result page. The result page will be passed the search id (generated in point 2) and the page number. Example result.aspx?searchId=5372947645&page=2
The result page will puck up the query from session using the searchId and then provide result based on the page number sent.
Using hidden fields and POST method should be fine too unless you are able to get them on the next page right.
To supplement Sarfraz's answer...
It's not necessary to use Javascript to make a POST.
<form action="destination_url" method="POST">
...
</form>

Categories