I want to be able to save data to a database or an external file in JavaScript. For example; you can have a high score variable in pong. The program checks if your current score is higher than the high score variable and changes when your score is higher. This is cool, but once you reload the tab, everything is reset. Anything that works I will except. Even changing the source code of the program is fine
Asked
Active
Viewed 7,570 times
0
-
This is extremely broad. Can you post data back to your server via AJAX? Does your program connect to a database already? Do you have external file resources? Have you looked into cookies or local storage? You say *Even changing the source code of the program is fine*: I can guarantee you that a change to the program is needed to add this feature. – Patrick M Nov 04 '14 at 21:53
-
Bonus points to anyone who can make this happen without changing the source code. – Raphael Serota Nov 04 '14 at 22:32
1 Answers
5
If you want to do this client-side, your options are basically:
- local storage
- cookies
Local storage is probably simplest:
var score = 1;
localStorage.score = 1;
Then later:
var score = parseInt(localStorage.score);
Note that everything you store in local storage is treated as a string. If you have a complex object, you'll have to convert it to JSON and back:
var players = {left:"tarzan", right:"jane"};
localStorage.score = JSON.stringify(players);
Then later:
var players = JSON.parse(localStorage.players);

Drew Noakes
- 300,895
- 165
- 679
- 742
-
@hackNightly, I tested this code in a JS console and it works, in Chrome at least. What is the advantage of the functions you suggest? – Drew Noakes Nov 04 '14 at 21:45
-
You'd actually be using localStorage, not setting properties on the global variable called 'localStorage'. – Hacknightly Nov 04 '14 at 21:47
-
1@hackNightly, I think you're mistaken. Open a JS console, enter the code I give, refresh your browser and check -- the values are still there. What's more, if you put `localStorage.a = {a:1}` then read out `localStorage.a` you'll get `"[object Object]"`. – Drew Noakes Nov 04 '14 at 21:49
-
1@hackNightly, the issue is discussed at length [in this SO question](http://stackoverflow.com/questions/12632463/is-localstorage-getitemitem-better-than-localstorage-item-or-localstoragei). They're pretty much equivalent, except for when keys are not present (undefined vs null). – Drew Noakes Nov 04 '14 at 21:51
-
Yup! Just checked and it worked. I had no idea, thank you for the enlightenment. – Hacknightly Nov 04 '14 at 21:51
-
Local storage would work for setting a personal high score, but you would never know if another user beat your score, since local storage is stored on the user's machine. If you want to have a true 'high score' functionality, you'll need a server of some sort. – Raphael Serota Nov 04 '14 at 22:35