Possible Duplicate:
What's the best way to pass a PHP variable to Javascript?
I have to do a function that automatically take care of passing variables from PHP to JavaScript in a simple and safe. Currently stored in a class variable array with the values of the variables, and then the idea is to extract in Javascript, but many doubts assail me what the (technically) best way to do this.
Also passes through my head several problems, especially when complex move to Javascript arrays or strings with accents, special symbols or symbols as quote or single quote, including problems with the function json_decode when work with chains with line breaks and carriage returns. (You get invalid JSON, I've had to do a cleaning function in PHP to avoid passing variables with these characters, but sometimes I need be)
I searched the web a lot, and I have found many answers but none terminade convince and more with the above problems.
An example:
The PHP Method (too simple):
var JsVars;
public function saveJsVar($key, $value) {
$this->JsVars[$key] = $value; //Possible need to clean certain characters like /n /r
}
The "javascript part"
<script>
var SistemVars = SistemVars || {};
<?php foreach ($JSVARS as $k => $var) { ?>
SistemVars.<?=$k?> = '' || '<?php echo $var ?>'; // Dont work with arrays only plain
<?php } ?>
</script>
Another option:
<script>
var SistemVars = SistemVars || {};
SistemVars = <?=json_encode($JSVARS)?> // Object, with plain and array BUT problems with certain characters.
</script>
The idea its use PHP (saveJsVar) to save plain variables and arrays, and set the vars in SistemVars object en JavaScript to use it like alert(SistemVars.ParamOne);
with your experience, what do you think is the best way to do this?