I want to pass an php array to js. For this purpose I use json_encode an then in js JSON.parse().
Now the Problem ist, that JSON.parse trow an exception 'missing ) after argument list'. I guess it's apostrophes in numbers (number_format > CHF).
clippings:
<script>
(function($) {
var prices = JSON.parse('<?= $this->prices_json; ?>'); ...
... "offsetdruck_4f":{"1s":"583.82","2s":"1'090.09"}...
- have single quotes to be escaped? If so, how best to do it?
- is json_encode an then in js JSON.parse the best practice to pass an php-Array to js (at a template)? If not, how best to do it?
I want to pass an php array to js. For this purpose I use json_encode an then in js JSON.parse().
Now the Problem ist, that JSON.parse trow an exception 'missing ) after argument list'. I guess it's apostrophes in numbers (number_format > CHF).
clippings:
<script>
(function($) {
var prices = JSON.parse('<?= $this->prices_json; ?>'); ...
... "offsetdruck_4f":{"1s":"583.82","2s":"1'090.09"}...
- have single quotes to be escaped? If so, how best to do it?
- is json_encode an then in js JSON.parse the best practice to pass an php-Array to js (at a template)? If not, how best to do it?
3 Answers
Reset to default 6have single quotes to be escaped?
Single quotes inside a JavaScript string literal that is delimited with single quotes do have to be escaped.
… and that is what you have: 'data with ' and then at the end'
.
If so, how best to do it?
To not use a JavaScript string literal at all.
JSON is a subset of JavaScript literal notation, so just treat it as JavaScript. Don't try wrapping it in a string and then explicitly parsing it.
var prices = <?= $this->prices_json; ?>;
try php: addslashes(json_encode($php array))
have single quotes to be escaped? If so, how best to do it?
json_encode should escape everything needs to be escaped.
is json_encode an then in js JSON.parse the best practice to pass an php-Array to js (at a template)? If not, how best to do it?
You should use json_encode in order to be sure that the output is correct. Do not rely on default array output. It has nothing to do with JSON.
You don't need to use JSON.parse here at all.
var prices = <?= json_encode($this->prices_json); ?>;