-4

I am trying to pass a variable to a php, I have tried the code below, but it was not working. Note: that the code below is just an example of what I am working on. I just made it that simple.

<script>
  var value = 0;
  alert("<?php echo"+value +" ?>");
</script>

3 Answers3

0

this is not possible. Javascript is client (browser) based, and php is server based.

0
<script>
  var value = 0;
  window.location.href = "myphpfile.php?value=" + value;
</script>

Replace myphpfile.php with your filename, then you can use the $_GET['value'] in your PHP code to display the variable.

e.g.

<?php
echo($_GET['value']);
?>
Stefano Sanfilippo
  • 32,265
  • 7
  • 79
  • 80
Dan Winduss
  • 11
  • 1
  • 4
0

PHP is a server-sided scripting language. The PHP script runs when your page loads so its impossible to put a Javascript variable in your page after the code ran. It might be possible when you post your Javascript variable in a form. You can also try posting it using jQuery without a page refresh.

Mark
  • 3,224
  • 2
  • 22
  • 30