I am trying create a bar chart for the data in mysql using php. I use bootstrap template to create application. I have predefined barchart with static data. I wanna add the data from the database. I tried my best but could not find solution as I am beginner in Javascript. Please guide me to add data dynamically. The Script is below:
// Bar chart
var ctx = document.getElementById("mybarChart");
var mybarChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: '# of Votes',
backgroundColor: "#26B99A",
data: [10, 20, 30, 40, 20, 10, 40]
}, {
label: '# of Votes',
backgroundColor: "#03586A",
data: [41, 56, 25, 48, 72, 34, 12]
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
<div class="x_content">
<canvas id="mybarChart"></canvas>
</div>
If I understand the environment, you have php-produced webpages.
If so I would:
Create a .php file
Write some php code to connect to the database and to retrieve an array with the data to be charted
Copy your JS code, wrapped in <script> </script> tags and also wrap it in a JS Function which you'll call later in the page
Inside your JS code, after datasets, write a php loop as this:
// Bar chart
var ctx = document.getElementById("mybarChart");
var mybarChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
<?php
if (count($arrayOfData) > 0){
echo "label: '# of Votes',";
echo "backgroundColor: '#26B99A',";
echo "data: [";
$firstValue = true;
foreach ($arrayOfData as $dataValue) {
if ( ! $firstValue ) {
echo ", ".$dataValue;
} else {
$firstValue = false;
}
echo $dataValue;
}
echo "]";
} else {
//Decide what to do if you don't have data
}
?>
}]
}'
Write the rest of the HTML/PHP page.
Note that if you want more than 1 bar in your graph you have to also cycle through different data sets, not only through one as I showed above for simplicity.
Related
I create a ApexChart with empty values because I dynamically add series and labels.
var options777 = {
chart: {
height: 397,
type: 'line',
toolbar: {
show: false,
}
},
series: [{
name: 'Elegibility',
type: 'column',
data: []
}],
stroke: {
width: [0, 4]
},
// labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
labels: [],
xaxis: {
type: 'datetime'
},
yaxis: [{
title: {
text: 'Elegibility',
}
}
};
var chart777 = new ApexCharts(
document.querySelector("#elegibilityChart"),
options777
);
if (document.getElementById('elegibilityChart')) {
chart777.render();
}
Then, I have a function that receives two arrays, one with the series data and other with label data. The arrays are same size, series contains numbers and labels strings.
function setData(mySeries, myLabels) {
chart777.updateOptions({
series: {
data: mySeries
},
labels: myLabels
})
}
When I run my code, it returns: error TypeError: "options$$1.series[0] is undefined"
How can I update the series and labels in the ApexChart?
Thanks
If you're updating both the series and the labels, this will need to be done in two separate calls.
Use the updateSeries method to provide the new data series (as an array).
Use the updateOptions method to provide the new labels (as an object that will merge with the existing options, keeping any configurations not overridden).
chart1.updateOptions({
xaxis: {
categories: year
},
series: [{
data: trend
}],
});
You should use code like this, I mean you should update xaxis categories instead of labels and also comment labels in options and instead use xaxis categories.
In my current project, I want to use Chart.js to display certain data from the database. Now I have the problem that I am not given any data, instead I always get the error message "$ is not a function" in Chrome.
I already tried some things, unfortunately without success.
I also included the latest version of JQuery at the top of my JS scripts.
The values of my MySQL database I get through a PHP script, which this out in JSON. There I get all the data.
My JS script calls:
<script src="vendors/jquery/dist/jquery.min.js"></script>
<script src="vendors/popper.js/dist/umd/popper.min.js"></script>
<script src="vendors/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="assets/js/main.js"></script>
<script src="assets/js/admin.js"></script>
<script src="vendors/chart.js/dist/Chart.bundle.min.js"></script>
<script src="assets/js/statistics/show-all-views.js"></script>
My Chart.js Code:
$(document).ready(function() {
$.ajax({
url: "http://localhost/fitnesslaeufer_cms/admin/includes/statistics/charts-data/show-all-views.php",
method: "GET",
success: function(data) {
console.log(data);
var views = [];
for(var i in data) {
views.push(data[i].score);
}
var ctx = document.getElementById("monthlyViews");
ctx.height = 50;
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"],
datasets: [
{
label: "My First dataset",
borderColor: "rgba(0,0,0,.09)",
borderWidth: "1",
backgroundColor: "rgba(0,0,0,.07)",
data: views
}
] ........
Use jQuery for your document and make sur to pass $ in the callback.
jQuery(document).ready(function($) {
// Your code here
});
I'm trying to use an array from my indexedDB, to plot a graph on Chart.js for my web application. I've attached the code from my javascript file where the array is obtained.
The array looks like this Objarr = ["34", "89"] and the numbers are added to the array when the user inputs these.
But I'm not able to say data: Objarr in my javascript code for the chart? Please, may you help me?
Javascript Code:
var chart = document.getElementById('lineChart').getContext('2d');
var lineChart = new Chart(chart, {
type: 'line',
data: {
labels: ["Jan", "Feb", "Mar", "April", "May", "June", "July"],
datasets: [{
label: " Peak flow values",
fill: false,
data: Objarr,
}
]
I am trying to show no data message when chart has no data.
Is it correct?
var ctx = document.getElementById('mycanvas').getContext('2d');
var chart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: ["aa", "bb", "cc", "dd"],
datasets: [{
label: "My First dataset",
backgroundColor: ['red', 'blue', 'green', 'yello'],
data: data.length ? data: [{ label: "No Data", value: 100 }],
}]
},
options: {
legend: {
position: 'right',
labels: {
boxWidth: 12
}
},
tooltips: { bodyFontSize: 12 }
}
});
I am not getting No data message when data length is 0.
Easiest is to use conditional rendering.
Assuming you're using AngularJS (you referenced tag), you can use ngIf directive. If data array is empty, then don't display chart.
<canvas id="myChart" ng-if="data != 0"></canvas>
<span ng-if="data == 0">No data</span>
Else, you can solve it in your script, by checking before or after draw the data length. I recommend you this snippet.
Other solution following your wish could be to adapt drawn data to received data.
if($scope.requestedLeaveTypeCount.length > 0){
data = {
labels: ["EL", "AL", "PL", "CL"],
datasets: [{
label: "My First dataset",
backgroundColor: ['#F0CB8C', '#A9D5D4', '#E8A3D7', '#CFA3FD'],
data: $scope.requestedLeaveTypeCount,
}]
}
} else {
data = {
labels: ["No data"],
datasets: [{
labels:'No data',
backgroundColor: ['#D3D3D3'],
data: [100]
}]
}
}
https://plnkr.co/edit/QXljAeeM4Ul3Y47EPcbq?p=preview
i try to display only the example from chart js in a project i work on. Unfortunately i'm forced to use Chart Js 1.x.
I tried to implement the bar example from https://github.com/chartjs/Chart.js/blob/master/samples/bar/bar.html
It's a pretty easy example i guess but it isn't running :(
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.1.1/Chart.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="zeitsteuerungChart"></canvas>
var barChartData = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: 'Dataset 1',
borderWidth: 1,
data: [
"1","1","1","1","1","1","1"
]
}, {
label: 'Dataset 2',
borderWidth: 1,
data: [
"1","1","1","1","1","1","1"
]
}]
};
window.onload = function() {
var ctx = document.getElementById("zeitsteuerungChart").getContext("2d");
var myBar = new Chart(ctx, {
type: 'bar',
data: barChartData
});
};
The Chart JS manipulate the
<canvas id="zeitsteuerungChart"></canvas>
element to
<canvas id="zeitsteuerungChart" width="300" height="150" style="width: 300px; height: 150px;"></canvas>
but thats pretty much it. No diagram shows up. No error in Console. I tried to use jQuery as well to select the canvas with
var ctx = $("#zeitsteuerungChart").get(0).getContext("2d");
but same effect! On other subpages of the project it's working pretty fine!
You are using chart js v2 syntax on v1.
for v1
var barChartData = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: 'Dataset 1',
borderWidth: 1,
data: ["1","1","1","1","1","1","1"]
},
{
label: 'Dataset 2',
borderWidth: 1,
data: ["1","1","1","1","1","1","1"]
}]
};
window.onload = function() {
var ctx = document.getElementById("zeitsteuerungChart").getContext("2d");
var myBar = new Chart(ctx).Bar(barChartData, options);
};
you can view chart options (chart js v1) here or complete options here