Reputation: 3579
I have this game board that stores the results of a tournament, and I can't figure out why the data (the game results being entered in through drop-down menu) gets erased when the browser is closed. Is there a way for my results to persist as long as the server is running?
The results are being displayed like this in main.js
:
$.post('/postScores', results, function(scores){
var gameBoard = "";
for(var j=0;j<scores.length;j++){
gameBoard+= '<tr>';
for(var k=0;k<5;k++){
gameBoard += '<td>'+scores[k][j]+'</td>';
}
gameBoard += '</tr>';
}
$("#grid").append(gameBoard);
});
And my scores are being stored in server.js
like this:
app.post("/postScores", function(req , res){
res.setHeader("Content-Type", "application/json");
var results = [
[ "", "team1", "team2", "team3", "team4"],
["team1", "x", req.body.e, req.body.h, req.body.k],
["team2", req.body.b, "x", req.body.i, req.body.l],
["team3", req.body.c, req.body.f, "x", req.body.m],
["team4", req.body.d, req.body.g, req.body.j, "x" ]
];
res.json(results);
res.end();
});
Full program: https://jsfiddle.net/Amidi/egp1hst3/10/
Upvotes: 2
Views: 45
Reputation: 3052
Use localStorage
like this.
var yourData = '';
localStorage.setItem('gameData',yourData);
to retrieve
var retrievedData = localStorage.getItem('gameData');
Keep in mind that you cannot store arrays in localStorage
, so you will have to stringify before you save to localStorage
and parse when you retrieve the data. Also keep in mind that you cannot store more than 5MB in localStorage
, which shouldn't be a problem for you. If you want persistence beyond the browser's cache, you will have to use a database of some kind.
Upvotes: 2
Reputation: 2775
when you use javascript to modify the currently viewed page, these changes are by nature temporary by design. The next time you load the same page, it will load the HTML structure from the browser again and present it in it's original state to you. This does make quite some sense, as you want the browser to render the page that the server sent to you and not something else.
if you want to do permanent changes to the UI, you will either need to store the state on the server and included the changes in the html response, or save state on the client (e.g. in cookies or localstorage) and then also apply the modifications from there once the page is loaded.
Upvotes: 4