0

I have below js code

<script type="text/javascript">
    var jvalue = 'Hi, $name';
</script>

And this is my php code

<?php
    $name= "Rama";
    $abc = "<script>document.write(jvalue)</script>";
    echo $abc;
?>

This is giving me output

Hi, $name

Instead of

Hi, Rama
Eldhose Elias
  • 389
  • 1
  • 6
  • 22
GRESPL Nagpur
  • 2,048
  • 3
  • 20
  • 40

3 Answers3

5

echo it. But Remember to follow the sequence of definition -

<?php
    $name= "Rama";
?>

<script type="text/javascript">
    var jvalue = 'Hi, <?php echo $name; ?>';
</script>

<?php
$abc = "<script>document.write(jvalue)</script>";
echo $abc;
?>
Sougata Bose
  • 31,517
  • 8
  • 49
  • 87
2

Try This one

<script type="text/javascript">

    var jvalue = "Hi, <?=$name;?>";
</script>

User double cot.

or best you can assing that php varible in input like this

<input type=hidden value="<?=$name; ?>" id='name'>

so you can access value of input using id anywhare on page. your script code will be

    <script src="//code.jquery.com/jquery.min.js"></script>
    <script type="text/javascript">
        $(function(){
          var jvalue = 'Hi, '+$('#name').val()+'';
        });
    </script>

I hope it will work for u as easy solution for now and for future.

Nitesh Pawar
  • 435
  • 2
  • 11
1

simple... try this

<?php 
$variable = "JS";
?>

<script>
   var field = <?php echo json_encode($variable); ?>;
  </script>