1

I am having trouble saving a variable that is given a variable with JS on a server. This variable cant be stored in cookies etc. because it needs to be accessable via other computers, aswell as on page reload (So it needs to be stored on-server.)

What is the best way to do this? Is it the most easy to start learning mySQL? this seems a bit to complicated for the simple task i want it to do. Is there another method e.g. saving it to a text file on the server's side?

7
  • How you store the variable is up to you, if a text file seems adequate, you'd use that. Commented Jan 3, 2016 at 11:27
  • If you want to store something basic from the frontend (what the user sees and where you JS variable is stored) to the server, you could use a simple form. This is the most common and easiest way to store something from the frontend on the server. Then, like @adeneo said, it is us to you, how you save it. But consider if that data could be considered confidential in any way. If you do not want the user to use form, you could execute the request with JavaScript. Have a look into AJAX. jQuery wraps up the functionality pretty good for beginners ;) Commented Jan 3, 2016 at 11:36
  • if it is something that is not changing you could think of using a config-file kind scenario. Commented Jan 3, 2016 at 11:38
  • U can save in cookie use php inside the javascript if yur javascript code in php file Commented Jan 3, 2016 at 11:45
  • You could do as vivoconnunxino suggests and make the file with comma separated values so you can get it back by reading the line(s) and using explode(); to put them into an array which you access in your PHP program. Commented Jan 3, 2016 at 12:17

1 Answer 1

1

You can use ajax along with jquery so the variable is sent from the client browser to your server script:

$.ajax({
    type: 'POST',
    url: 'script_which_stores_variable.php',
    dataType: 'html',
    data: {
        'foo' : foo,
    }
});

Then, script_which_stores_variable.php can save that foo value in many different ways:

$var = $_POST['foo'];
file_put_contents('file_where_stored_value_is.php', $var);

or an insert to your database (if any).

Sign up to request clarification or add additional context in comments.

1 Comment

What you are presenting here is not a vanilla JS version. It would be good, if you would mention that you are using jQuery.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.