1

I am new to PHP. I want to pass the php variable into my javascript file. But it was not converted. I already defined the value of $val in php file. I write following code in my index.js file;

var val = "<?php echo $val ?>";
console.log(val);

but my console shows output as : <?php echo $val ?>. It is not taking the php variable value. Any help?

4
  • 2
    PHP does not run on .js files. Commented Oct 26, 2019 at 8:42
  • I follow dyn-web.com/tutorials/php-js/…. this tutorial. Commented Oct 26, 2019 at 8:43
  • 1
    @Tekson Where does that tutorial say that you can put the PHP code in a .js file? It says you're supposed to put it in the JavaScript segment of a PHP script. Commented Oct 26, 2019 at 8:49
  • Ok I got that thank you. I insert It into js file. But actually I have to insert above expression in php file using <script> tag. That solved my issue. Commented Oct 26, 2019 at 8:55

1 Answer 1

0

you have to include script at bottom of your page PHP FILE

  <script>
   var val = "<?php echo $val ?>";
   console.log(val);
  </script>
Sign up to request clarification or add additional context in comments.

2 Comments

Actually, I write the code on the js file directly. I connect both php file and js file in same html file.
As above suggestion, I put my code into php file using <script> tag. This solve my issue. My mistake was I doen't put my code into js file. js can't run php file. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.