How to embed PHP code in JavaScript?

Web Development

How can we use PHP code in JavaScript?

Like

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

Please suggest a better way.
 


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.

1
Answers

Replies

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); ?>;


</script>


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.

 
 

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.
WhatsApp
To Top