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.
We can't use "PHP in between JavaScript", because PHP runs on the server and JavaScript - on the client. However we can generate JavaScript code as well as HTML, using all PHP features, including the escaping from HTML one.
There are two ways of calling a PHP function from JavaScript depending on your web project's architecture: You can call PHP function inline from the <script> tag. You can use fetch() JavaScript method and send an HTTP request to the PHP server.
Besides, PHP and JavaScript similarities, these two languages are a powerful combination when used together. Large numbers of websites combine PHP and JavaScript – JavaScript for front-end and PHP for back-end as they offer much community support, various libraries, as well as a vast codebase of frameworks.
rich1812. Hi, I search google, the general consensus is that php will not work in script tag, I accept that.
If your whole JavaScript code gets processed by PHP, then you can do it just like that.
If you have individual .js
files, 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:
<script type="text/javascript"> var my_var = <?php echo json_encode($my_var); ?>; </script>
You could then use my_var
in 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.
If you put your JavaScript code in the PHP file, you can, but not otherwise. For example:
page.php (this will work)
function jst() { var i = 0; i = <?php echo 35; ?>; alert(i); }
page.js (this won't work)
function jst() { var i = 0; i = <?php echo 35; ?> alert(i); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With