Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I embed PHP code in JavaScript?

Tags:

javascript

php

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.

like image 985
Amit Sharma Avatar asked Jul 28 '10 11:07

Amit Sharma


People also ask

Can you embed PHP in JavaScript?

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.

Can you execute PHP in JavaScript?

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.

Can PHP and JavaScript work together?

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.

Can we write PHP code in script tag?

rich1812. Hi, I search google, the general consensus is that php will not work in script tag, I accept that.


2 Answers

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.

like image 80
reko_t Avatar answered Sep 21 '22 03:09

reko_t


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); } 
like image 26
Sarfraz Avatar answered Sep 24 '22 03:09

Sarfraz