1

I understand that this question has been asked a lot of of times, but the solutions posted there don't seem to work for me. I have a code as follows:

<script>
  var JSvar = "<?php echo $phpVar ?>";
  document.write(JSvar);
</script>
<?php 
$phpVar="jajha";
?>

I actually want to pass a PHP variable to a JS function, but I wanted to try if printing the variable works first. Please help me out.

  • it won't work if you don't define it first (you should get an error for that, too) – Damien Pirsy Jul 21 '15 at 15:15
  • 5
    PHP and Javascript cannot time travel... And even if this was working, DON'T spit php output directly into a JS context. use `json_encode()` to guaranteed you're outputting syntactically correct JS. – Marc B Jul 21 '15 at 15:15
  • 1
    [Please, don't use `document.write()`!](http://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice) – D4V1D Jul 21 '15 at 15:19

1 Answers1

0

instead of

<script>
  var JSvar = "<?php echo $phpVar ?>";
  document.write(JSvar);
</script>
<?php 
$phpVar="jajha";
?>

try

<?php 
    $phpVar="jajha";
    ?>
<script>
    var JSvar = "<?php echo $phpVar ?>";
    document.write(JSvar);
</script>
jrath
  • 930
  • 4
  • 14