Send JavaScript variable to PHP variable [duplicate]

PHP runs on the server and Javascript runs on the client, so you can’t set a PHP variable to equal a Javascript variable without sending the value to the server. You can, however, set a Javascript variable to equal a PHP variable:

<script type="text/javascript">
  var foo = '<?php echo $foo ?>';
</script>

To send a Javascript value to PHP you’d need to use AJAX. With jQuery, it would look something like this (most basic example possible):

var variableToSend = 'foo';
$.post('file.php', {variable: variableToSend});

On your server, you would need to receive the variable sent in the post:

$variable = $_POST['variable'];

Leave a Comment