-3

I am trying to send a php array to jquery

This is my array before json encode:

Array ( [0] => 30-Dec [1] => 31-Dec [2] => 1-Jan [3] => 2-Jan [4] => 3-Jan [5] => 4-Jan [6] => 5-Jan [7] => 6-Jan ) 

This is it after the json encode:

["30-Dec","31-Dec","1-Jan","2-Jan","3-Jan","4-Jan","5-Jan","6-Jan"]

If I make a variable in jquery with the json encoded array and print this in the console I got the following:

[&quot ;30-Dec&quot ;,"31-Dec&quot ;,&quot ;1-Jan&quot ;,&quot ;2-Jan&quot ;,&quot ;3-Jan&quot ;,&quot ;4-Jan&quot ;,&quot ;5-Jan&quot ;,&quot ;6-Jan&quot ;]

But then without the spaces between the t and ;

I am using twig and silex for my websites.

EDIT
This is my code PHP code

function getDates($startTime, $endTime) { $day = 86400;

        $format = 'j-M';

        $startTime = strtotime($startTime);

        $endTime = strtotime($endTime);

        $numDays = round(($endTime - $startTime) / $day) + 1;

        $days = array();

        for ($i = 0; $i < $numDays; $i++) {

            $days[] = date($format, ($startTime + ($i * $day)));

        }

        return $days;

    }

    $days = getDates($lastday, $today);

    $days = json_encode($days);

This is my twig/jquery code

var days = '{{ days }}';

console.log(days);

6
  • I don't think this is the result of json_encode. json_encode should be returning json, shouldn't it? Commented Jan 6, 2015 at 17:11
  • 4
    So.... What is your code? Commented Jan 6, 2015 at 17:13
  • problem isn't with json_encode , far more likely a result of running it through templating engines. Read the manual docs for json_encode Commented Jan 6, 2015 at 17:20
  • Show the code where you encode the array, where you pass it to the view, and how you echo it in the view. Commented Jan 7, 2015 at 6:26
  • Why don't you use Silex's helper to return a JSON Response? Commented Jan 7, 2015 at 9:11

2 Answers 2

1

Deciding how to present a given set of data to the user is the role of the view layer. Remove the json_encode call from your php code, it should return a simple array. Pass that to twig and do the encoding there:

{{ days|json_encode }}
0

As noted before by charlietfl the templating Engine/Twig is escaping your data. An easy fix should be applying the |raw filter [0].

[0] http://twig.sensiolabs.org/doc/filters/raw.html

Your Answer

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.