JavaScript jQuery inside PHP function

javascript, jquery, php

Solution

Yes, it's okay to do that. No, it's probably not a good idea. But there's nothing really stopping you.

Just be aware that if your variable happens to have a `'` in it, you'll get messed up.

So, whenever you want to pass a variable from PHP to JavaScript, be sure to use `json_encode`:

<script type="text/javascript">
    alert(<?php echo json_encode($something); ?>);
</script>

Note that there's no quotes in the JavaScript part - `json_encode` will add quotes if needed. This can be used to pass almost any kind of variable.

Problem

This is a theoretical question. My question is whether a jQuery function or script can be written inside a PHP function. E.g. ``` <?php function phpfunc(){ $a=10; ?> <script>var a ='<?php $a ?>'</SCRIPT> <?php } ?> ``` Is this possible and legal?

Original source