If I write php code inside a javascript method does the php code execute if the method of the javascript is not called at all ?
-
Yes if javascript code will written in PHP file – amit Dec 29 '15 at 12:21
-
2Welcome to SO. Please read [What topics can I ask about](http://stackoverflow.com/help/on-topic) and [How to ask a good question](http://stackoverflow.com/help/how-to-ask) And [the perfect question](http://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/) – RiggsFolly Dec 29 '15 at 12:26
-
PeterssonJesper gave you a good answer. Also, the php will always run on the server before the javascript on the client runs ... or does not run. – Yogi Dec 29 '15 at 12:33
5 Answers
The PHP code runs on the server, meanwhile the Javascript code runs on the client. The PHP code will always run, no matter of what Javascript you try to surround it with.

- 211
- 2
- 2
PHP is a server side scripting so that is always run let me explain it with code.
There is no issue for PHP script code work with js. just you need to do this in .php
file only.
For example:
example.php
<?php
//Initialize PHP variable value...
$htmlString= 'Hello testing'; ?>
<!-- Use PHP variable into JS -->
<script type="text/javascript">
// notice the quotes around the ?php tag
var htmlString="<?php echo $htmlString; ?>";
alert(htmlString);
</script>
And this will prompt message "Hello testing".
Hope this help you!

- 21,025
- 5
- 26
- 57
If you want to write php code inside javascript then you can write like following :
var message_from = <?php echo $_SESSION['user']['user_id'] ?>;
These links may help you:
PHP code inside a Javascript's "document.write()"

- 1
- 1

- 921
- 1
- 7
- 22
Yes dear, Your PHP code will run always. as PHP is server side wheres JavaScript is Client side. so when you called page Both method run simultaneously. so no matter if you defined PHP code inside JavaScript.

- 1,665
- 2
- 20
- 42
If it is inside a PHP tag and inside a PHP file, it will run the code, no matter what or where it is.

- 580
- 4
- 22