3

Yes I know this question gets asked a lot, but I'm fairly new to JS and I need to use a php variable in some JS. I'm more then aware that PHP is executed server side and JS is client side however other people claim that this works.

I've got a PHP variable called "test1" that I want to log to the JS console (for instance):

 <?php
 $test1 = '1';

 print '
 <script type="text/javascript">
      var carnr;        
      carnr = "<?php print($test1); ?>"
      console.log(carnr);
 </script>';
 ?>

What this does is print " " to the JS console. Not exactly what I was hoping for.

Now this may not even be doable and I may have to pass the variable off the page and back in again with AJAX, but I'd rather have a quick and easy solution if there is one available!

Any help is appreciated.

Compy
  • 1,157
  • 1
  • 12
  • 24

6 Answers6

13

You could do this.

<script>
    var JSvar = "<?= $phpVar ?>";
</script>

The PHP will be parsed and the value of $phpVar will become the value of JSvar whatever.

Make sure you encode phpVar properly. For example, if phpVar contains a double quote, you'll end up with a broken JS

Gopinagh.R
  • 4,826
  • 4
  • 44
  • 60
7

Use this no need to give "" => change to '.$test1.'..

<?php
 $test1 = '1';

 print '
 <script type="text/javascript">
      var carnr;        
      carnr = "'.$test1.'"
      console.log(carnr);
 </script>';
 ?>
MKV
  • 913
  • 7
  • 6
3

try

<?php $test1 = '1'; ?>
<script type="text/javascript">
  var carnr;        
  carnr = "<?php print($test1); ?>"
  console.log(carnr);
</script>

Generally, it is better to not print static stuff with php, but to have static (that is unchanging) stuff directly in HTML and only use PHP on the parts that really need it.

til_b
  • 327
  • 5
  • 15
2

You made a mistake do it so:

<?php
 $test1 = '1';

 echo '<script type="text/javascript"> var carnr; carnr = "'.$test1.'" console.log(carnr)</script>';
?>
idmean
  • 14,540
  • 9
  • 54
  • 83
  • This is a bad answer... Why is it getting upvoted. – Jeff Shaver Mar 15 '13 at 13:56
  • @JeffShaver And why is it a bad answer? – idmean Mar 15 '13 at 13:56
  • 1
    It is long and unnecessary. Why echo it onto the page when you can just get of out "PHP" mode, put the js and then just go back to echo the value? It will work, but it definitely isn't a good way to do it. It also isn't as easy to to read – Jeff Shaver Mar 15 '13 at 13:58
0

Since you're writing your JS with your PHP, you can simply do:

$test1 = "blah";

echo "<script type=\"text/javascript\">console.log($test1);</script>";
Major Productions
  • 5,914
  • 13
  • 70
  • 149
-2

You are already in open php tag. When printing the line just append the variable to the output by using a dot.

Example:

print 'variable1 '.$variable1.' is now printed';
LordShigi
  • 25
  • 1
  • 4