parse array in charts js laravel blade - javascript

I need show temperature monthly to charts in laravel
my view page consist
temp.blade
<script>
console.log({!! $temp !!});
console.log({!! $dateTemp !!});
window.onload = function() {
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: {!! $temp !!},
datasets: [{
label: 'Temperature',
data: {!! $dateTemp !!},
borderWidth: 1
}]
}
});
}
</script>
and controller
public function tempChart()
{
$temp = Temps::select(DB::raw('temp'))
->orderBy('date_temp','asc')
->get();
$temp->implode(',',$temp);
$dateTemp = Temps::select(DB::raw('temps'))
->select('date_temp')
->orderBy('date_temp','asc')
->get();
$dateTemp->implode(',',$dateTemp);
//dd($temp,$dateTemp);
return view('report/temp')
->with('temp',$temp)
->with('dateTemp',$dateTemp);
}
it can not show data array but it show
[{...}],[{...}],[{...}]

I am not sure which Chart library you are using but most of them wants an array of strings or integer and you give them array of objects.
I think that you just need to convert your array in the php (or in the javescript)
php way:
$temp = Temps::select('temp'`)
->orderBy('date_temp','asc')
->get()
->pluck('temp');
$dateTemp = Temps::select(['temps', 'data-temp'])
->orderBy('date_temp','asc')
->get()
->pluck('data-temp'); // I am not whats the acual query you want but this is the idea
and then if you using laravel 5.5 just write on your blade
<script>
window.onload = function() {
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: #json($temp),
datasets: [{
label: 'Temperature',
data: #json($dateTemp) ,
borderWidth: 1
}]
}
});
}
</script>

Try add high comma to Data?
datasets: [{
label: 'Temperature',
data: '{!! $dateTemp !!}',
borderWidth: 1
}]

Related

How to set action on slice-click Doughnut in Chart.js

I've been trying to add chart.js to my Django Project, which worked pretty fine so far. I made a doughnut-chart with two slices. Now i want to have each of those slices to have seperate actions on click, like for example redirecting to new side.
These are my chart settings:
var config = {
type: 'doughnut',
data: {
datasets: [{
data: {{ data|safe }}, // Error because django and js are being mixed
backgroundColor: [
'#ff0000', '#008000'
],
label: 'Population'
}],
labels: {{ labels|safe }}
},
options: {
responsive: true
}
};
And this is the rendering and my function to make the actions on click:
window.onload = function() {
var ctx = document.getElementById('pie-chart').getContext('2d');
var myPieChart = new Chart(ctx, config);
$('#myChart').on('click', function(event) {
var activePoints = myPieChart.getElementsAtEvent(event)
if(activePoints[0]){
console.log("Helo 1")
}
else {
console.log("helo 2")
}
})
};
I saw my solution on other pages, but it doesn't work at all. Am I missing something? If yes could you please help?
getElementAtEvent has been replaced with chart.getElementsAtEventForMode in Chart.js v3 (see 3.x Migration Guide).
Please take a look at below runnable code and see how it works now:
const pieChart = new Chart("myChart", {
type: 'pie',
data: {
labels: ["Red", "Blue", "Yellow"],
datasets: [{
data: [8, 5, 6],
backgroundColor: ["#FF6384", "#36A2EB", "#FFCE56"],
}]
},
options: {
onClick: evt => {
var elements = pieChart.getElementsAtEventForMode(evt, 'index', { intersect: true }, false);
var index = elements[0].index;
console.log(pieChart.data.labels[index] + ': ' + pieChart.data.datasets[0].data[index]);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
<canvas id="myChart"></canvas>

Integrate PHP variables in Javascript [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 2 years ago.
I have this Javascript which outputs a chart with some values:
<script type="text/javascript">
//pie
var ctxP = document.getElementById("pieChart").getContext('2d');
var myPieChart = new Chart(ctxP, {
type: 'pie',
data: {
labels: ["Red", "Blue"],
datasets: [{
data: [10, 90],
backgroundColor: ["#F7464A", "#46BFBD"],
hoverBackgroundColor: ["#FF5A5E", "#5AD3D1"]
}]
},
options: {
responsive: true
}
});
</script>
I need to customize some values, as the ones in labels or data, coming from some calculations previously made in PHP.
What I tried so far was unsuccessfull, probably because I am missing something.
To simplify what I did, here the code:
//PHP code where I define some variables as strings
<?php
$color1 = "Black";
$color2 = "White";
?>
//Then comes again the Javascript code:
<script type="text/javascript">
//pie
var ctxP = document.getElementById("pieChart").getContext('2d');
var myPieChart = new Chart(ctxP, {
type: 'pie',
data: {
labels: [<?php echo $color1, $color2; ?>], //////////Here my modification
datasets: [{
data: [10, 90],
backgroundColor: ["#F7464A", "#46BFBD"],
hoverBackgroundColor: ["#FF5A5E", "#5AD3D1"]
}]
},
options: {
responsive: true
}
});
</script>
This does not work, but I do not understand why.
I also tried with:
<?php
$colors = array("Black", "White");
?>
passing the $colors variable, but nothing changes.
What kind of mistake am I making?
How can I fix this?
In a php file it can be done with json_encode
<?php
// your php code
?>
<script>
var jsObject = <?php
echo json_encode([
'my_variable1' => 'value1',
'my_variable2' => 'value2'
]);
?>
console.log(jsObject);
</script>

How can I plot data from an external JSON file to a chart.js graph?

I would like to chart data from an external JSON file using chart.js. As an example, the json file here lists movies ("title") and ratings ("rt_score"). I'd like to be able to show each movie and its rating without including the static JSON in the .js file, but rather using the $.ajax call method to refer to the /films endpoint.
I'd like to have:
labels: labelsVariable
data: dataVariable
Here is a fiddle with the setup so far with static data.
Here's my HTML:
<body>
<canvas id="myChart" width="400" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js">
</script>
</body>
Here's the js that successfully generates a bar chart like I want, but with static data in "labels" and "data" instead of referencing the JSON file.
var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Castle in the Sky', 'Grave of the Fireflies'],
datasets: [{
label: 'rating',
data: [95, 97],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
Instead of using the static data and labels, how can I reference the external JSON file using the $.ajax call method?
Based on what I've read, I may have to use "map" to break down the objects into arrays that contain labels and data?
Thank you in advance.
I think you are looking for Ajax request to fill your chart.
function getRandomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var ctx_live = document.getElementById("mycanvas");
var myChart = new Chart(ctx_live, {
type: 'bar',
data: {
labels: [],
datasets: [{
data: [],
borderWidth: 1,
borderColor:'#00c0ef',
label: 'liveCount',
}]
},
options: {
responsive: true,
title: {
display: true,
text: "Chart.js - Dynamically Update Chart Via Ajax Requests",
},
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
}
}]
}
}
});
var postId = 1;
var getData = function() {
$.ajax({
url: 'https://jsonplaceholder.typicode.com/posts/' + postId + '/comments',
success: function(data) {
myChart.data.labels.push("Post " + postId++);
myChart.data.datasets[0].data.push(getRandomIntInclusive(1, 25));
// re-render the chart
myChart.update();
}
});
};
setInterval(getData, 3000);
see live example here.
Load the json chart data dynamically and set it when you are creating the graph. There are many ways you can load the chart json data. However, I believe the JQuery getJSON function is more relevant to you.
$.getJSON( "chartdata/test.json", function( data ) {
var myChart = new Chart(ctx, {
type: 'bar',
data: data,
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}
I figured it out. Here's what worked. I had to use .map to set up the data properly inside variables and then use those variables as data and labels.
function renderChart(data, labels) {
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'This week',
data: data,
}]
},
});
}
function getChartData() {
$("#loadingMessage").html('<img src="./giphy.gif" alt="" srcset="">');
$.ajax({
url: "https://ghibliapi.herokuapp.com/films",
success: function (result) {
var data = result.map(x=>x.rt_score);
var labels = result.map(x=>x.title);
renderChart(data, labels);
console.log(data);
},
});
$("#renderBtn").click(
function () {
getChartData();
});

Data not displaying in Chart JS from PHP JSON

Hi I'm trying to display a dynamic line chart using Chartjs with data pulled from SQL using PHP in JSON format. The data is successfully selected but does not successfully display just a blank chart, any help is appreciated.
$(document).ready(function() {
var dataPointsA = []
var dataPointsB = []
$.ajax({
type: 'GET',
url: 'data.php',
dataType: 'json',
success: function(field) {
for (var i = 0; i < field.length; i++) {
dataPointsA.push({
x: field[i].datetime,
y: field[i].roomtemp
});
dataPointsB.push({
x: field[i].datetime,
y: field[i].tanktemp
});
}
console.log(field);
var chartdata = {
title: {
text: "Fish Tank Monitor"
},
data: [{
type: "line",
name: "line1",
dataPoints: dataPointsA
}, {
type: "line",
name: "line2",
dataPoints: dataPointsB
}, ]
};
console.log(chartdata);
var ctx = mycanvas.getContext('2d');
var barGraph = new Chart(ctx, {
type: 'line',
data: chartdata,
backgroundColor: 'rgba(0, 119, 204, 0.3)'
});
}
});
});
Example JSON
[{"datetime":"2018-07-28 22:33:00.000","roomtemp":26.9,"tanktemp":28.4},{"datetime":"2018-07-28 22:32:00.000","roomtemp":26.9,"tanktemp":28.4},{"datetime":"2018-07-28 22:31:00.000","roomtemp":26.9,"tanktemp":28.4},{"datetime":"2018-07-28 22:30:00.000","roomtemp":26.9,"tanktemp":28.4},{"datetime":"2018-07-28 22:29:00.000","roomtemp":26.9,"tanktemp":28.4},{"datetime":"2018-07-28 22:28:00.000","roomtemp":26.9,"tanktemp":28.4},{"datetime":"2018-07-28 22:27:00.000","roomtemp":26.9,"tanktemp":28.4},{"datetime":"2018-07-28 22:26:00.000","roomtemp":26.8,"tanktemp":28.4},{"datetime":"2018-07-28 22:25:00.000","roomtemp":26.9,"tanktemp":28.4},{"datetime":"2018-07-28 22:24:00.000","roomtemp":26.9,"tanktemp":28.4}]
I think its happeing due to incorrect date time format. datetime key you used is acting as a string. I think you need to apply one date and time filter

Chart.js with Django - Using REST

Using Django rest frame work i have my query set-up and pulling my data to a url like below. I'm trying to get the data in to chart.js. I can manage to get it to the console or plot the first result, but no further any assistance would be greatly appreciated
"comp_history_data": [
[
"(2017, 01, 20)",
256.0
],
[
"(2018, 01, 20)",
456.0
],
[
"(2018, 02, 20)",
568.0
],
[
"(2018, 03, 20)",
683.0
]
],
Here is what i have in my HTML, works fine with dummy data, just not too sure how to plot with the data above
<script>
var endpoint = '/api/chart/data/'
var defaultData = []
var labels = [];
$.ajax({
method: "GET",
url: endpoint,
success: function(data){
labels = data.labels
defaultData = data.comp_history_data.forEach(functoin(entry){
console.log(entry)
setChart()
},
error: function(error_data){
console.log("error")
console.log(error_data)
}
})
function setChart(){
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx2, {
type: 'line',
data: {
labels: labels,
datasets: [{
label: '# of Computers',
data: defaultData,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
],
borderColor: [
'rgba(255,99,132,1)',
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
}
</script>
Small Edit: I can get one item onto the graph with the code below, so looks like the data is coming through OK, just need to separate
<script>
var endpoint = '/api/chart/data/'
var defaultData = []
var labels = [];
$.ajax({
method: "GET",
url: endpoint,
success: function(data){
labels = data.labels
defaultData = data.comp_history_data.forEach(functoin(entry){
console.log(entry)
setChart()
},
error: function(error_data){
console.log("error")
console.log(error_data)
}
})
function setChart(){
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx2, {
type: 'line',
data: {
labels: labels,
datasets: [{
label: '# of Computers',
data: defaultData[0],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
],
borderColor: [
'rgba(255,99,132,1)',
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
}
</script>
Any thoughts on how i use the data array i have with chart.js I would like the 0 the data to be along the bottom with the numbers plotted on the graph
Thanks again
Remember to include <canvas id="myChart"></canvas> within your html file.
That might be all you need. If not, this is a working function I have - I've not changed my variable names to match your's but I think it easy to understand.
success : function(json) {
// Add graph
var chartLabels = json.categories.map(function(e) {
return e.name;
})
var chartValues = json.values.map(function(e) {
return e;
})
var ctx = document.getElementById("myChart");
var data = {
labels: chartLabels,
datasets: [{
"label" : json.startRegulation[0].name,
"data" : chartValues,
"fill" : true,
"backgroundColor":"rgba(255, 99, 132, 0.2)",
"borderColor":"rgb(255, 99, 132)",
"pointBackgroundColor":"rgb(255, 99, 132)",
"pointBorderColor":"#fff",
"pointHoverBackgroundColor":"#fff",
"pointHoverBorderColor":"rgb(255, 99, 132)"
}]
}
var options = {
"elements":
{"line":{"tension":0,"borderWidth":3}
},
scale : {
ticks : {
min : 0,
}
}
}
var myChart = new Chart(ctx, {
type: 'radar',
data: data,
options : options,
});
Try to change :
defaultData = data.comp_history_data.forEach(functoin(entry){
to :
defaultData = data.comp_history_data.forEach(function(entry)){
Also, read the usage of template filters (Django) maybe you will find them helpful.
For instance, from your views.py file send data :
def MyView(request):
comp_history_data: ['1', '2', '3']
return render(request, 'chart.html', {'comp_history_data':comp_history_data})
and then in your HTML file print the vars :
{% for var in comp_history_data %}
{{ var }}
{% endfor %}
Hope it helps
It looks like you have an error in your success function, as below
defaultData = data.comp_history_data.forEach(functoin(entry){
to:
defaultData = data.comp_history_data.forEach(function(entry){

Categories

Resources