Php inside javascript

Is it ok to call php inside javascript?
For example:

<script type="text/javascript">("<? echo "test"; ?>");</script>

It works fine for me but I don’t understand why some people say that it doesn’t work.

Somebody wrote:
“To understand why your approach is not working, it’s really important to remember that JavaScript runs on the client and PHP on the server. As Spookster has already said above, when PHP is done with processing a file, it sends the output as a HTTP response back to the client. So generally, these two technologies can’t be interoperable, since they don’t run in the same environment.”

Is it possible that it works because I am running it on my computer but when it will be on shared hosting it wont work?

I’ve never seen a problem with using PHP inside of javascript for the exact reason you’ve posted. PHP is run server side and javascript is run client side. So the PHP is processed before the HTML/javascript is even sent to the browser. As far as the javascript/browser is concerned, it’s the same as the rest of the HTML that’s getting sent over from the web server.

Presumably, your page is named .php so if your PHP were to freak out and stop working for some reason your entire page wouldn’t work anyway. You’re not even creating any additional points of failure from a reliability standpoint.

Some people try to call PHP functions/code “from JavaScript” – that’s what people refer to when they say that using PHP in JavaScript doesn’t work.

For example, this:


<?php
function doStuff() {
    doMoreStuff();
}
?>
<script>
window.onload = function() {
    <?php doStuff(); ?>
}
</script>

But outputting things within a JavaScript tag from PHP isn’t an issue. PHP doesn’t know and doesn’t care that the PHP code was put inside some JavaScript tags, and the browser doesn’t know or doesn’t care that PHP wrote that JavaScript.

Maybe page 1 and 2 help clear it up for you.