-1

For example, I have this on my js

<script>
  var calc=7;
</script>

and I want to use the value from js in php and I want to store the value in php variable

<?php
  $charge.
?>
Tom Aranda
  • 5,919
  • 11
  • 35
  • 51
Acema
  • 1
  • 1
  • 2

2 Answers2

0

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script>
var calc=7;
function sendvariable() {
   $.post('your_file.php',{calc:calc}, function(data) {
      console.log('['+data + ']');
      
   });
       }
</script>
and your php file :

<?php
$charge = $_POST['calc'];

echo $charge;

?>

normally it works

Robin
  • 126
  • 9
0

You have a few options:

The best way, in my opinion, is to use AJAX. This will make a call to your PHP script in the background. You can use jQuery, a helper library, to make things easier:

<script>
var calc = 5;
$.ajax("submit.php", {
    data: { "calc": calc },
    type: "POST"
});
</script>

If you don't want to use jQuery, it's possible to make an AJAX call without it. Take a look around the internet for using XMLHttpRequest to make a POST request.

Another way is to use <form method="post"> and <input> tags (type="hidden" if needed) and then send the data using a submit button. Unlike AJAX, this isn't done in the background and redirects the user to another page.

<form id="form" method="post" action="submit.php">
    <input id="calc" name="calc" type="hidden">
    <button type="submit">Submit Data</button>
</form>

<script>
var calc = 5;
document.getElementById("form").onsubmit = function () {
    document.getElementById("calc").value = calc;
};
</script>

In all of these examples, the values of the the data you send will show up under PHP's $_POST variable:

<?php var_dump($_POST["calc"]); ?>
vqdave
  • 2,361
  • 1
  • 18
  • 36