2

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

asked Jul 25, 2013 at 21:26
8
  • 1
    why did you use htmlentities/htmlspecialchars? Commented Jul 25, 2013 at 21:26
  • Show how you are using the var in JavaScript. Commented Jul 25, 2013 at 21:27
  • @BadWolf: That's a very bad idea. Yes, don't use htmlentities. No, don't just output it directly. Commented Jul 25, 2013 at 21:28
  • I edit my post with my code Commented Jul 25, 2013 at 21:31
  • setDayArray('<?php $dayArray ?>'). That's your problem right there, you have to echo it out. Commented Jul 25, 2013 at 21:31

2 Answers 2

4

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
answered Jul 25, 2013 at 21:27
Sign up to request clarification or add additional context in comments.

1 Comment

I have the same problem setDayArray([&quot;L&quot;,&quot;M&quot;,&quot;M&quot;,&quot;J&quot;,&quot;V&quot;,&quot;S&quot;,&quot;D&quot;]);
1

I find the solution

calendar.setDayArray({{ dayArray | raw }});

use raw to allow html

answered Sep 8, 2013 at 22:24

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.