0

I have a list of numbers in my pageController.php

$half2018 = [235, 1234, 134, 564, 364, 362];
return view('page', 'half2018'=>$half2018); 

I call that variable in my page.blade.php

<canvas id="chart_1" class="chart-canvas" data-info="{{ $half2018 }}"></canvas>

Then at the end of page.blade.php I have

<script src="./assets/js/chart.js"></script>

In my chart.js file I call

let app = document.getElementById('claims_chart_12');
let info = JSON.parse(app.dataset.id);
console.log(info);

For some reason, JSON library is not loaded. Is it a right way to pass the data to .js file?

Wolf Walker
  • 73
  • 1
  • 7

2 Answers2

1

The syntax in your controller should be

$half2018 = [235, 1234, 134, 564, 364, 362];

return view('page', ['half2018' => $half2018]);

or

return view('page', compact('half2018'));

In your blade file, you can set the variable in a data-* attribute after it's converted to valid JSON. Use single quotes for it.

<canvas id="chart_1" class="chart-canvas" data-info='{{ json_encode($half2018) }}'></canvas>

I think this is equivalent to

<canvas id="chart_1" class="chart-canvas" data-info='@json($half2018)'></canvas>

Then, in your js, you can parse this JSON.

let canvas = document.getElementById('chart_1');
let info = JSON.parse(canvas.dataset.id);
console.log(info);
IGP
  • 14,160
  • 4
  • 26
  • 43
0

@IGP pointed out my syntax in Controller.php. After I changed the line in chart.js file to

let info = JSON.parse(canvas.dataset.info);
console.log(info)

then I get

[235, 1234, 134, 564, 364, 362]

in my .js file.

Wolf Walker
  • 73
  • 1
  • 7