How to embed PHP code in JavaScript?

Web Development

How can we use PHP code in JavaScript?


function jst()
var i = 0;
i = <?php echo 35; ?>

Please suggest a better way.



Ans: If the whole javascript code gets processed by PHP, then you do it the same way. However, if you have a set of individual javascript files represented in .js files, and if you would not like PHP to process the same, then you will need to pass the variables around in the Javascript.

 Let us take an example of index.php, the below script can be used.

<script type="text/javascript">

    var my_variable = <?php echo json_encode($my_variable); ?>;


You can use the my_variable in the Javascript files. This method also allows you to pass any other other than integer values, as json_encode() is also included or deals with the strings, arrays, etc.


If you want to unleash your potential in this competitive field, please visit the Web Development course page for more information, where you can find the Web Development tutorials and Web Development frequently asked interview questions and answers as well.


This topic has been locked/unapproved. No replies allowed

Login to participate in this discussion.

Leave a reply

Before proceeding, please check your email for a verification link. If you did not receive the email, click here to request another.
Protected by Astra Security