Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

handling javascript files containing php code

I need to add via addJs method javascript code, that is dynamically created and dependent of php variables.

I got all javascript at the end of the page, so I want core js files to load first and then my custom file to be loaded - that is why I cannot do it in the view.

So I parsed it as a view with partial, and now I need to somehow pass it to addJs method. How it can be done, or mayby there is a more natural way to do that?

UPD: I got custom files of .pjs extensions interpreted as php code but assigned Content-Type header of application/javacsript. How do I handle them inside of phalcon?

You should be outputing the variables to an inlined <script> tag and not trying to load a specific file. You can then pickup on said variables in your main script.



969

You should be outputing the variables to an inlined <script> tag and not trying to load a specific file. You can then pickup on said variables in your main script.

That is not what I need.



3.7k
Accepted
answer

I think you'll find it's only what you think you want.

What you are asking for does not make sense so I'm going to keep pointing you away from it, because if you knew how to code it, you'd know it's wrong, and in most cases extremely inneficient.

A static file is meant to be static. Having a dynamic view is allready enough of a load for us to worry about so people engineered systems's like phalcon in zephir/c.

Javascript has loaders that could load the right file or files conditionnaly. Config vars should be in the main or sub scripts and potentially overloaded on a view per view basis (inline). That's were you get the dynamic part you want.

Prove me wrong or describe the problem rather than the expected output if I'm trolling you, but i'm 90% sure I'm not.

edited Jan '15

Having server-side code (PHP) inside client-side code (JavaScript) its a bad practice. They were made for, and should, work independently and communicate via some kind of API if a communication is needed.

A better approach would create your JavaScript code receiving some parameters that you send via your server-side code. Example:

// JavaScript
function mySuperFuncion(param1, param2){
    if(param1 === undefined || param2 === undefined){
        throw "I need two parameters to work properly.";
    }
    // do something with param1 and param2
}

And then (assuming you will not use AJAX for it) you could call this funcion into your view (for example) passing the variables like:

{# Volt view #}
<!-- ... -->
<button onclick="mySuperFunction({{param1}}, {{param2}})">Run my super awesome function!</button>
<!-- ... -->