-1

I'm quite new to JavaScript so I hoped I could get some help with these questions. I need to save a JavaScript variable (Just a simple number) to a database. I also need to be able to see the current value on 2 websites (using PHP to retrieve it on the second website).

My code now:

Voorraad: <input id="stock1" type=text" style="width:30px" value="10">

<input type="submit" value="Kopen" onclick="javascript:Kopen(event);">

<script src="http://code.jquery.com/jquery-latest.js"></script>
    <script type="text/javascript">
function Kopen(e)
{
  e.preventDefault();
  var stock1 = document.getElementById("stock1");
  var newNumber = parseInt(stock1.value) - 1;
  stock1.value = newNumber;
  if (stock1.value <= 0) {
      stock1.value = 0;

  }

I know I will need to use AJAX to do this, I have seen a question that is similar but it lacks a database connection and I am not sure how to use those pieces of code: Question

My questions are; How do I write a JavaScript variable to (mysql)database using ajax?

Community
  • 1
  • 1
Bonny
  • 29
  • 3

1 Answers1

0

You can transfer data from PHP to javascript by writing a javascript object into you script file:

<script>
var data_object = {
"id": <?php echo data->id ?>,
"role": <?php echo data->name ?>
}
</script>

This object is now available in the page via Javascript.

console.log(user_object.data)

In this way you can use your java script variable in server side script. Hope this will work out.

Aman Garg
  • 3,122
  • 4
  • 24
  • 32
  • Can you explain what the purpose is of the seperate parts (id, role), and where to implement this? – Bonny Jun 27 '16 at 16:06
  • I just wrote it as an example, you can take the reference only. Its not the exact answer. And parts(id, role) are database fields that fetched using the query. – Aman Garg Jun 28 '16 at 07:28