I have data am looping from controller and i have a graph script and i want to loop that data in the script so that it can draw the graph based on that data
In controller i have
$records = Products::select('price')->get();
and in blade i have
<script>
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
theme: "light2",
title:{
text: "Simple Line Chart"
},
data: [{
type: "line",
indexLabelFontSize: 16,
dataPoints: [
@foreach($records as $prc)
{ y: $prc->price},
@endforeach
]
}]
});
chart.render();
}
</script>
Original script
<script>
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
theme: "light2",
title:{
text: "Simple Line Chart"
},
data: [{
type: "line",
indexLabelFontSize: 16,
dataPoints: [
{ y: 500 },
{ y: 400 },
{ y: 250 },
{ y: 310 }
]
}]
});
chart.render();
}
</script>
Its giving me a blank page, how can i go about doing it
CodePudding user response:
Solution from @Aless55 works perfectly fine
<script>
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
theme: "light2",
title:{
text: "Simple Line Chart"
},
data: [{
type: "line",
indexLabelFontSize: 16,
dataPoints: [
@foreach($records as $prc)
{ y: {{$prc->price}} },
@endforeach
]
}]
});
chart.render();
}
</script>
CodePudding user response:
Try this piece :
<script>
window.onload = function () {
var records = "<?php echo $records ?>"
var data = records.map((function (record) {
return {y: record.price}
}))
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
theme: "light2",
title:{
text: "Simple Line Chart"
},
data: [{
type: "line",
indexLabelFontSize: 16,
dataPoints: data
}]
});
chart.render();
}
</script>