Pass variables from PHP to JS

General discussion about MantisBT Plugins

Moderators: Developer, Contributor

Post Reply
LukeWCS
Posts: 10
Joined: 11 Mar 2021, 13:22
Location: Germany

Pass variables from PHP to JS

Post by LukeWCS »

Normally I would solve this in the PHP script as follows:

Code: Select all

echo '<script>';
echo $config_vars;
echo '</script>';
echo '<script type="text/javascript" src="{external_script}"></script>';
However, this does not seem to be allowed with Mantis, since the developer console of the browser receives a message that this has been blocked by "Content Security Policy". How can I then pass variables to a JS script? I can't find anything about this in the developer documentation, or I haven't found it yet.
atrol
Site Admin
Posts: 8398
Joined: 26 Mar 2008, 21:37
Location: Germany

Re: Pass variables from PHP to JS

Post by atrol »

Might help, check javascript_config.php and javascript_translations.php
Please use Search before posting and read the Manual
LukeWCS
Posts: 10
Joined: 11 Mar 2021, 13:22
Location: Germany

Re: Pass variables from PHP to JS

Post by LukeWCS »

Hi atrol

Thank you for your answer and your hint. With these two files alone, I didn't understand how it worked. It wasn't until I also included html_api.php that I realized how it works, I think. If I understand correctly, a JS script is included, which was generated by PHP. But in that case I would have inline JS again which is blocked by CSP, or not?

Regardless of that, I've also found 2 other solutions in the meantime:

1. I hadn't thought of this solution at first, but I used to work with it a lot with Perl: Passing variables in the query string to JS. But that is quite cumbersome, at least in the JS script which has to evaluate the parameters. "A lot" of code is necessary.
2. I like the second solution, on the other hand, very much and my plug-in now also works with it: Define the desired variables with "data-" directly in the script call and then read them out in the JS script via jQuery. It works very well and requires minimal code for it.

Nevertheless, thank you for your information. The more alternatives you know, the better. :)
LukeWCS
Posts: 10
Joined: 11 Mar 2021, 13:22
Location: Germany

Re: Pass variables from PHP to JS

Post by LukeWCS »

@atrol

I had a mistake in reasoning. I took a closer look at it and now it is clear to me what you meant. For this, however, I would need another PHP script with which I can then dynamically generate the JS script. In principle no problem, but it is much more effort than the "HTML data- * Attributes". The script generation method could be advantageous if there were a lot of config variables. In my case, however, there are only 3 variables that I have to pass.
Post Reply