0

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

2
  • 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. Commented Nov 4, 2014 at 21:53
  • Bonus points to anyone who can make this happen without changing the source code. Commented Nov 4, 2014 at 22:32

1 Answer 1

5

If you want to do this client-side, your options are basically:

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);
Sign up to request clarification or add additional context in comments.

6 Comments

@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?
You'd actually be using localStorage, not setting properties on the global variable called 'localStorage'.
@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]".
@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).
Yup! Just checked and it worked. I had no idea, thank you for the enlightenment.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.