-8

In my php script I have variable like below.

$duration = 60;

Now I'm accessing the above PHP variable in javascirpt.

<script type="text/javascript">
    var phpVar = '<?php echo $duration; ?>';
    console.log(phpVar );
 </script>

But in the console I'm getting the whole data instead of 60. That is, output is

 '<?php echo $duration; ?>'

Please help me how to access the php variable properly.

Thanks.

7
  • Whatever file you put this in, did not get parsed as PHP. stackoverflow.com/questions/23574306/… Commented May 10, 2019 at 9:00
  • It's working with single quotes, double quotes and without quotes, there is no issue with the code, make sure you file as .php Commented May 10, 2019 at 9:01
  • 1
    you shouldn't mix PHP + JS like this - they get executed differently. Much better to use AJAX and get the value from a script, assign it to a var that way. Commented May 10, 2019 at 9:01
  • You're setting $duration but echoing $simple. However the PHP output suggests you've saved the file as *.html instead of *.php Commented May 10, 2019 at 9:02
  • $duration or $simple? Commented May 10, 2019 at 9:02

1 Answer 1

-1
<script type="text/javascript">
  $(document).ready(function(){
  var phpVar = <?php echo $duration; ?>;
  console.log(phpVar);
});

Put $duration instead if $simple.

Sign up to request clarification or add additional context in comments.

2 Comments

eidited the question with $duration. But it is not evaluating the php statement. It is considering as normal string.
I tried this same code. it's running perfect

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.