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
-
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– Patrick M2014-11-04 21:53:23 +00:00Commented Nov 4, 2014 at 21:53
-
Bonus points to anyone who can make this happen without changing the source code.Raphael Serota– Raphael Serota2014-11-04 22:32:54 +00:00Commented Nov 4, 2014 at 22:32
Add a comment
|
1 Answer
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);
6 Comments
Drew Noakes
@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?
Hacknightly
You'd actually be using localStorage, not setting properties on the global variable called 'localStorage'.
Drew Noakes
@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
@hackNightly, the issue is discussed at length in this SO question. They're pretty much equivalent, except for when keys are not present (undefined vs null).
Hacknightly
Yup! Just checked and it worked. I had no idea, thank you for the enlightenment.
|