I'm using an MVC setup and I'm trying to inject javascript into my views (.php), yet allow the javascript access to all the variables that the view has access to. My end goal is to be able to access PHP variables from my javascript (for example so I could alert()
a product's name).
Here's my application flow:
- start output buffer
- call extract() on an associate array (this contains the data for my view)
- call require on the view file
- return the contents of the output buffer, and clear the buffer
- echo buffer
I have a function injectJS()
, which is as follows:
function injectJS($jsFile) {
require APP_DIR . $jsFile;
}
Here's a sample of the Javascript (alert.js) I want to inject:
<script type="text/javascript">
alert("product name: <?php echo $product['name']; ?>");
</script>
So, within my view file, I call injectJS('alert.js');
. It injects the javascript, but I get a PHP notice of having an undefined variable $product
when I render the view. However, if I write the require
statement by hand, everything works fine. Is what I'm trying to achieve by using injectJS()
possible?
Edit
I forgot to mention that I did try passing the variables explicitly to injectJS()
, and it does work, but I don't want to have to always pass the variables. It could become messy & cumbersome if the view needs to pass many variables to the JS. Is there a way I could (within the function) grab the variables within the scope of the script responsible for calling the injectJS()
?
Edit 2
On second thought, passing the variables again is not a real issue, I think I'm just being greedy/lazy ;). I will just pass the variables when needed to injectJS()
. Thanks for the responses