PHP runs server side to create the page, and JS runs on the client side with the page already created. The only way they "talk" is via ajax.
If you are using a framework, such as zend and etc, you usually use a template engine to work with variables in HTML, you can also pass these variables to JS, example of using variables with the template engine RainTpl
// include require "library/Rain/autoload.php"; // namespace use Rain\Tpl; $config = array( "tpl_dir" => "vendor/rain/raintpl/templates/test/", "cache_dir" => "vendor/rain/raintpl/cache/" ); Tpl::configure( $config ); $t = new Tpl; $t->assign('title','Hello!'); $t->draw('test');
or simply do so
<?php $variavel = "texto"; ?> <script> var variavel = "<?php echo $variavel; ?>"; </script>
However, depending on the case, this can be done through an AJAX request where JS will send a request to the server and obtain a response, asynchronously, without interrupting its application. So, with that answer in JS, you can do whatever you want.