John Doe
John Doe

Reputation: 601

Ajax call at Laravel route that returns an json encoded array containing dates for ChartJS labels

I have a Laravel 5.7 project, with ajax and ChartJS.

At page load, I am making an ajax call to "action_route", which returns the labels for my ChartJS. The php function is json encoding an array of labels, and the ajax decodes them.

function get_data($year) {
    $test = \DB::select( \DB::raw("
        SELECT 
            DATE_FORMAT(date_for,'%c/%y') AS 'month',
            col1,
            col2,
            col3
        FROM test
        WHERE
            AND YEAR(date_for) = '" . $year . "'
        GROUP BY month
        ORDER BY month ASC
    ") );

    return $test;
}

public function action_route() {
   $data = self::get_data(2018);
   foreach($data as $x) {
      $labels[] = $x->month;
   }
}

return view('/test/get_data', [
     'labels' => json_encode($labels)
]);

DATE_FORMAT(date_for,'%c/%y') AS 'month' - Because I need dates if this format: '01/18', '02/18' etc.

In template:

var labels = JSON.parse('{{ $labels }}');

The Problem This is what get's put into html.

enter image description here

Upvotes: 1

Views: 224

Answers (1)

Rwd
Rwd

Reputation: 35190

When using {{ }} laravel will escape the data it displaying. To stop it escaping the data you should wrap it in {!! !!} instead i.e.

var labels = JSON.parse('{!! $labels !!}');

For more information you can check out the Docs

Upvotes: 2

Related Questions