SyntaxError: expected expression, got '&'

3671 views javascript
7

I do a loop on my controller:

$events = '[';
while ($init->format('w') != $agenda->day){
    $events = $events . "{title: 'test', start: '" . $init->format('Y-m-d') . "'},";
    $init->add(new DateInterval('P1D'));            
}
$events = $events . ']';

the result is this string:

[{title: 'test', start: '2018-09-15'},{title: 'test', start: '2018-09-16'},]

On my blade page, I have a script to generate a fullcalendar and I put the code on it:

events:
    {{$eventos}},

But inside the script my code change to:

[{title: 'test', start: '2018-09-15'},{title: 'test', start: '2018-09-16'},]

and I receive the error:

SyntaxError: expected expression, got '&'

How to do the script read ' rather than '?

answered question

Don't try to build JSON yourself, php has a function for generating json: json_encode.

@PatrickEvans how do I convert my strings on json using json_encode? I am noob ^^

1 Answer

7

Instead of creating the json string in your loop, define an array to pass to the view.

$events = []; 
while ($init->format('w') != $agenda->day){
    $events[] = [
        'title' => 'test', 
        'start' => $init->format('Y-m-d')
    ];
    $init->add(new DateInterval('P1D'));            
}

Then in the view file use the @json blade directive to output your array as json.

events: @json($events);

posted this

Have an answer?

JD

Please login first before posting an answer.