Reputation: 10089
I have a php variable which contain json, I use json_encode to transform an array to json.
If I print my var I have:
["L","M","M","J","V","S","D"]
But if I use my var in js I have:
["L","M","M","J","V","S","D"]
and I can't parse because I have an error
Uncaught SyntaxError: Unexpected token &
Is there a way to get json in my js ?
Thanks
Edit:
In php
$dayArray = array('L','M','M','J','V','S','D');
$dayArray = json_encode($dayArray)
In js
setDayArray('<?php echo $dayArray ?>');
setDayArray = function(dayArray){
console.log(dayArray);
}
With twig
calendar.setDayArray({{ dayArray }});
This is maybe due to symfony rendering, the only way I found is to do an ajax call using json header
Upvotes: 2
Views: 837
Reputation: 10089
I find the solution
calendar.setDayArray({{ dayArray | raw }});
use raw to allow html
Upvotes: 1
Reputation: 1074335
To output JSON in PHP, output the result of passing your PHP structure through json_encode
.
Example from the documentation:
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
Outputs:
{"a":1,"b":2,"c":3,"d":4,"e":5}
Re your updated question, you've used
$dayArray = json_encode($dayArray)
setDayArray('<?php $dayArray ?>'); // Wrong
Get rid of the quotes, and include echo
unless it's magically getting output some other way:
$dayArray = json_encode($dayArray)
setDayArray(<?php echo $dayArray ?>); // Right
When you do that, the browser will see something like:
setDayArray(["L","M","M","J","V","S","D"]); // Right
rather than
setDayArray('["L","M","M","J","V","S","D"]'); // Wrong
Upvotes: 4