var b ="$a";
Is there a better way of doing this? Yes, absolutely. In general you don't want blocks of executable JS statements residing in a PHP script. This just muddles things up and makes them very tough to maintain. I would prefer to actually have JS request the value through an AJAX call to a PHP service. If you must use this approach, I would still separate concerns a little better.
EDIT: This works for me:
<html> <head> <title>PHP-JS Writer</title> </head> <body> <?php $a = "cat"; echo "<script>var b = '$a'</script>"; ?> Writing JS variables with PHPAnswer2:
<script> alert(b); </script> </body> </html>
<?php $a = "some value"; ?> <script> var a = <?php echo json_encode($a); ?>; console.log(a); </script>
You can use this for more complex structures as well:
<script> var a = <?php echo json_encode(array('property' => 'value')); ?>; console.log(a.property); </script>