MyBB Community Forums

Full Version: best practice for using PHP variables in JS files?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I've reached somewhat of a snag in the remake of my plugin. My shoutbox uses a single javascript file which controls the entire client-side functionality. Of course, I want have the user's dynamic plugin settings be available to the javascript code. Take this code snippet for example:

this.flood_limit = {$settings['inferno_shoutbox_flood']};

A PHP setting for the shoutbox (an integer in this case) is being eval()'d into the javascript code. This is all fine and dandy, but the issue here is that if someone were to view the source of a page using this shoutbox, halfway down would be hundreds of lines of javascript inside of script tags. Ideally, I would want to have this javascript file referenced externally in the script tag so the js isn't shown directly in the source for the page. The problem with this is that the PHP variables which are included cannot be parsed this way, because it's a javascript file.

I got around this in the last version by naming the file shoutbox.js.php which got the job done because it parsed it as PHP, but this seems kind of shotty. I feel like there must be some better solution to this issue.

Aside from being aesthetically pleasing, services like CloudFlare cache css and javascript files on their servers and by injecting the javascript into the html as in the picture above, it bypasses this as it is not a legitimate javascript file.
You could do what MyBB does and just define the variables in the HTML and access them from the script file. There aren't really many better ways.