When you are building an application where settings are set serverside with PHP, what's the best way to communicate these settings to Javascript on pageload?
Why set all settings serverside and not partly clientside, partly serverside? Because the app is certainly in PHP, but the Javascript part may be written in plain Javascript, JS Prototype, jQuery, ... So this way we remain one set of PHP functions for the whole app independent of the Javascript layer.
I have been thinking of a couple of solutions myself:
1. Via a hidden form field:
<input typ="hidden" name="settings" value="JSON encoded settings" />
Disadvantages:
2. With Ajax
As soon as the page loads, there is an ajax post request to the server which retrieves the settings.
Advantages:
Disadvantages:
3. Directly via the source settings file (XML)
Advantages:
Disadvantages:
4. Something else?
Edit: added one advantage for number 2
Any format like yaml, json, xml, etc. is ok because you can read it with PHP and transform it into each of the formats.
Maybe the best solutions in your case is a json formatted configuration file. You can read that directly with both JS and PHP when needed.
The Zend Framework has a nice JSON encoding/decoding component.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With