I have a web page with 3 elements where a user will enter a text value and then press a button. On submit, it will process and return some values to be populated in a table.
This part works fine.
Now if the user refreshes the page, all the data is gone and the 3 elements and the table looks empty.
I would like to do this. Catch the refresh event and store the 3 user entered values in a local storage and when the page is loading back up, I will send this back to the controller to populate the tables again.
Is this possible to do? I am pretty new to web development and am running out of ideas.
This is what I tried. And this doesn't work.
window.onbeforeunload = function() {
localStorage.setItem(name, $('#name_field').val());
localStorage.setItem(id, $('#id_field').val());
localStorage.setItem(pw, $('#pw_field').val());
alert("am here")
}
window.onload = function() {
var name= localStorage.getItem(name);
if (name != null) $('#name_field').val(name);
var id= localStorage.getItem(id);
if (id!= null) $('#id_field').val(id);
var pw= localStorage.getItem(pw);
if (pw!= null) $('#pw_field').val(pw);
}
I could never get the alert in window.onbeforeunload function to pop up.
You can store it everytime on the local storage(or event session storage, which I think its better in your case). Then everytime you look after that value on the storage. In case of any value found, you send it to the controller.
If it was me I would do as I said above, save your data into the sessionStorage(what means that the data will be lost if user closes the tab/browser):
var saveData = function()
{
var data =
{
id: $("#id_field").val(),
name: $("#name_field").val(),
pw: $("#pw_field").val()
};
sessionStorage.setItem("formValues", JSON.stringify(data));
}
Idk if your post is async or not. If its async, you can call that function on your successCallback, if it isn't async, call it on the submit event.
Then at ready event, you can read that data:
$(document).ready(function()
{
var data = sessionStorage.getItem("formValues");
// Check if there is any user data already saved
if (data)
{
data = JSON.parse(sessionStorage.getItem("formValues"));
$("#id_field").val(data.id);
$("#name_field").val(data.name);
$("#pw_field").val(data.pw);
}
});
I prefer to store a group of data in an object into a single key on the storage, that is why I use JSON to stringify and parse an object, because storage only accepts string types.
A simple advise: Don't - ever - store passwords, let the user type it. For security reasons.
Related
I want to store the data which is imputed by the user using a form and vanilla JS.
So when I reopen the the page any data pushed to the arrays are still visible when logged to the console.
I have done some research and understand using Json is the answer (I think).
I have done some research but everything I found seemed to use Node.js.
Any links or code would be very appreciated.
Note: I can post more of the code if needed, the code posted is the function which is executed once the form is submitted.
const formEl = document.getElementById('mainForm');
const comment = document.getElementById('comment');
formEl.onsubmit = function (e) {
//Selecting the comment input on the form to pass to the
//comment waiters array.
const comment = document.getElementById('comment').value;
//Selecting the choosen index from the user food and which waiter orderd //it which waiter.
//Selects the choosen food to pass to the addFood method in the waiter //class.
const foodItemIndex = foodMain.options[foodMain.selectedIndex].value;
const foodItem = mainFood[foodItemIndex];
//Selecting the waiter to push valid informaiton to.
const waiterName = waitersEl.options[waitersEl.selectedIndex].value;
const waiter = waiters.find(({name}) => name === waiterName);
//Logic to check when submited if both feilds are true proceed.
//The statements check to see which feild values have been entered
//Then it call's the corresponding method from the waiter class and
//pushes the value to the choosen array
if (waiter && foodItem && comment) {
waiter.addFood(foodItem)
waiter.addComment(comment);
console.log(waiters);
}
else if (waiter && comment) {
waiter.addComment(comment);
console.log(waiters);
}
else if (waiter && foodItem){
waiter.addFood(foodItem)
console.log(waiters);
}
formEl.reset();
return false; // prevents redirect/refresh
};
After the form has been submitted once:
0: Waiter
comment: ["This form has been submitted I will now close the window and when I reopen I will not be here"]
name: "Timo"
order: [Item]
total: 14
Now when I reopen:
0: Waiter
comment: []
name: "Timo"
order: []
total: 0
I want it so when I reopen the data is still inside the array.
If you only want to use JavaScript, you can use either cookies or LocalStorage.
LocalStorage is a type of web storage that allows Javascript websites
and apps to store and access data right in the browser with no
expiration date. This means the data stored in the browser will
persist even after the browser window has been closed.
LocalStorage works like this:
const person = {
name: "Obaseki Nosa",
location: "Lagos",
}
window.localStorage.setItem('user', JSON.stringify(person));
To retrieve the user key stored above:
window.localStorage.getItem('user');
This returns a string with value as;
"{“name":"Obaseki Nosa","location":"Lagos"}"
In order to get the values of everything in local storage, use:
Object.entries(localStorage)
To use this value, you would have convert it back to an object.
To do this, we make use of JSON.parse() method which converts a JSON string into a Javascript Object.
JSON.parse(window.localStorage.getItem('user'));
However, if you want this to be an application and is not a form of homework, I would suggest saving and then getting back the data through the server (for example by using PHP and a MySQL database).
I'm a new learner for API, and I have a quesion about local storage. This is a code example from my javascript book:
if (Modernizr.localstorage) {
var txtUsername = document.getElementById('username');
var txtAnswer = document.getElementById('answer');
txtUsername.value = localStorage.getItem('username');
txtAnswer.value = localStorage.getItem('answer');
txtUsername.addEventListener('input', function () {
localStorage.setItem('username', txtUsername.value);
}, false);
txtAnswer.addEventListener('input', function () {
localStorage.setItem('answer', txtAnswer.value); }, false);
}
}
I want to ask why should we "localStorage.getItem()" part? Cause I think if user type their username, then we can get their names just from the variable "txtUsername" cause I thought it should be setItem first and then getItem. Thank you!
Local storage is used to store small amounts of data on the client side. What does your code ?!
For example: A user visited the site for the first time and complete the inputs, , the data stored in the local store. The user closed the browser. The next day he again went to the site to fill out the form again, and its data is already filled. Conveniently!
Also we can use local storage as js object
txtUsername.value = localStorage.getItem('username');
txtUsername.value = localStorage.username;
txtUsername.value = localStorage['username'];
The thing is, it works just as you said.
It's just, when person types data in the textbox he uses setItem - that what 'input' eventListener used for
Think of LocalStorage as of really light database that keeps data even when user closes the page
But since it can store data when page is closed, you want to show the content of it in the textbox - and that's why author uses 'getItem' on start
ISSUE
I have been trying to update a field (gamesArray) from the current User (Parse.User.current()), so later in another view I can see it. The problem is that when I do it, the field gets updated (I console.log() it right after the object is saved and check it on the Database UI from Parse) but when I go to the other view, in which the User is retrieved and I show the field on screen, it is not updated.
CONTEXT
My _User has an array of Games called gamesArray so I update that array just like this:
addGameToUser = function(game, userId) {
var userQuery = new Parse.Query(Parse.User);
userQuery.equalTo("objectId", userId);
userQuery.first({
success: function(user) {
// User found
},
error: function(error) {
console.log(error.message);
}
}).then(function(user) {
// If user is current user update it
if(user.id == Parse.User.current().id) {
var games = user.get('gamesArray');
games.push(game);
user.set('gamesArray', games);
user.save(null, {
success: function(user) {
console.log(user.get('gamesArray'));
},
error: function(user, error) {
console.log(error);
}
});
}
else {
// Call cloud function...
}
});
}
In this case, console.log(user.get('gamesArray')) returns the updated field. I use this function when the user creates a new game.
The problem is that in a different view, when I retrieve the user and get that field, it is not updated:
getUserGames: function() {
var games = Parse.User.current().get('gamesArray');
console.log(games);
}
Here, console.log(games) is printing the old field value. So if I had 4 games in the array, the previous function printed 5 (4 plus the created one) and this still prints 4.
I thought that maybe I was not saving the Game properly, but this is the output of the Parse's Database UI gamesArray column of the current User:
[{"__type":"Pointer","className":"Game","objectId":"..."}]
The only way that I can get the updated field is logging out and logging in with the same user.
QUESTIONS
Why is that? What am I doing wrong? How could I "update" the user so I don't have to log out?
It sounds like your user object that you are reading from is not the same specific object that you are updating. So you are updating the object in your database, but the user object you're reading from doesn't know that the object in the database has been updated. You should try fetching the user first. iOS has a fetchIfNeeded method.
I am having an issue with a project I am working on using phonegap
[Step 1] -
I am storing a users login "session" locally (Web SQL) from a web server. This is working fine, I can successfully connect to the web server, post the user login data, get a response from the server, create the local User database and store the user "session" value
[Step 2] - I then need to pass this "session" value back to the web server, and receive response data from the server. Again, this works as expected but the problem is, the callback function is being executed twice.
Step 2 is called when the user taps a button on the screen, and it doesn't seem like the reason that Step 2 is being called twice if because phonegap is picking up the tap more than once, I have tried:
$(".yes_sync").live("tap", function(){
console.log("tap!");
...
Which only logs a single tap event.
When the user taps I am calling:
var db = window.openDatabase("MVIdb", "1.0", "MVIsqlite", 200000);
db.transaction(getUserId, getUserIdFailed, getUserIdsSuccess);
The getUserId, getUserIdFailed and getUserIdsSuccess functions look like so:
function getUserId(tx){
tx.executeSql("SELECT * FROM user WHERE id = '1'", [], getUserIdsSuccess, getUserIdFailed);
}
function getUserIdFailed(tx, results){
console.log("Error retrieving user session ID");
}
function getUserIdsSuccess(tx, results){
console.log("Success retrieving user session ID");
if(typeof results != 'undefined'){
var return_value = results.rows.item(0).user_id;
user_session_id = return_value;
var token = $.md5(user_session_id+"whatever!");
$.get('http://localhost/project/dummyserver/sync?user_id=' + user_session_id + '&token=' + token, function(data) {
data = $.parseJSON(data);
for (var key in data){
console.log(data[key]['user_id']);
}
$(".ui-loader").fadeOut();
jQuery.mobile.changePage("_sync_complete.html", { role: "dialog", transition: "pop" } );
});
}
}
As you can see, the last line in the callback for the $.get in the callback for the success opens a pop up dialogue. This dialogue is being called twice.
I have noticed that phonegap has a lot of asynchronous behaviour, which I understand is to prevent the system from feeling "laggy", but surely it shouldn't be executing a callback function on a db.transaction more than once?
Your callback is called twice because you are passing it both to the executeSql command and the transaction. Remove it from one to make it work as expected.
Not the most elegant solution, but I went with using a global variable
var has_getUserIdsSuccess = false;
And in the callback function:
if(typeof results != 'undefined'){
if (has_getUserIdsSuccess == false){
has_getUserIdsSuccess = true;
// as per above
has_getUserIdsSuccess = false; // set it back to false so use can press the execute this function again later
}
I am still interested to see if anyone has a better solution!
I'm using Lawnchair, and I've managed to store a value locally. Something like this:
var Users = new Lawnchair({table:'Users', adaptor:'dom'});
function save_prompt()
{
var UserName = prompt("Your Username","John Doe");
if (UserName!=null && UserName!="")
{
Users.save
({key:'UserData', SavedUserName:UserName});
}
}
function recall_prompt()
{
Users.get
('UserData',function(r)
{
document.getElementById('Message').innerHTML = r.SavedUserName;
}
);
}
I call both functions save_prompt & recall_prompt using buttons binded with onclick.
Basically this script will pop up a textfield to enter your username (John Doe is default) and saves it.
With recall_prompt, it worked fine by showing the saved username in the html div id="Message".
My question is, how to save a second, third, and beyond usernames? And how to retrieve them all to show in the html div? I've tried numerous methods that can be found on the 'net but I just can't get it to work. It seems the new username always overwrites the old ones.
Lawnchair saves data as Key:value pairs. So if u save another username with the same key, (UserData), it'll always get overridden. To save more usernames u'll have to change the keys. Make it UserData_1, UserData_2, like that.
Or you could store an array of usernames with the key 'UserData', so each time u need to save a username, get the array from DB, then add the new username to it and resave it.