DADU
DADU

Reputation: 7048

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:

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

Upvotes: 5

Views: 438

Answers (2)

markus
markus

Reputation: 40675

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.

Upvotes: 2

tybro0103
tybro0103

Reputation: 49703

php can generate javascript you know...

<script type="text/javascript">
    var my_var = '<?php $my_var ?>';
</script>

Upvotes: 2

Related Questions