Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to communicate PHP settings to Javascript?

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:

  • Directly viewable in the source code.
  • Input hidden is meant to submit hidden data, not to get data.

2. With Ajax

As soon as the page loads, there is an ajax post request to the server which retrieves the settings.

Advantages:

  • Clean
  • Clientside can request only the settings it needs.

Disadvantages:

  • Heavier page load

3. Directly via the source settings file (XML)

Advantages:

  • Javascript and PHP code are completely decoupled (concerning the settings).

Disadvantages:

  • Settings file is loaded twice (serverside + clientside)

4. Something else?

Edit: added one advantage for number 2

like image 976
DADU Avatar asked Oct 14 '22 19:10

DADU


1 Answers

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.

like image 89
markus Avatar answered Nov 15 '22 09:11

markus