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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If your whole JavaScript code gets processed by PHP, then you can do it just like that.
If you have individual
.jsfiles, and you don’t want PHP to process them (for example, for caching reasons), then you can just pass variables around in JavaScript.For example, in your
index.php(or wherever you specify your layout), you’d do something like this:You could then use
my_varin your JavaScript files.This method also lets you pass other than just simple integer values, as
json_encode()also deals with arrays, strings, etc. correctly, serialising them into a format that JavaScript can use.