PHP Array seen as single element in Chartjs - javascript

I have two arrays in PHP which I am trying to pass to a Chart to be displayed in Chartjs.
The following code creates the arrays by using a foreach on a multidimensional array to extract them.
<?php
$behaviours = orderByType($_SESSION['loggedStudent']['studentID']);
$behTypes = array();
$behValues = array();
foreach($behaviours as $item){
$behTypes[] = $item["type"];
$behValues[] = intval($item["count(*)"]);
}
// php arrays to JSON
$behaviourLabels = json_encode($behTypes, TRUE);
$behaviourValues = json_encode($behValues, TRUE);
?>
<canvas id="pie-chart" width="800" height="450"></canvas>
<script>
// parse to js
var strLables = <?php echo($behaviourLabels); ?>;
var strValues = <?php echo($behaviourValues); ?>;
// parse as array
var arrLables = JSON.parse($strLables);
var arrValues = JSON.parse($strValues);
new Chart(document.getElementById("pie-chart"), {
type: 'pie',
data: {
labels: arrLabels,
datasets: [{
label: "Incident Type",
backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
data: arrValues,
}]
},
options: {
title: {
display: true,
text: 'Breakdown of incident types for <?php echo($_SESSION['loggedStudent']['firstName']); ?>'
}
}
});
</script>
No chart or labels are showing. What am I doing wrong?

The expected values for both data and labels are array.
What you need to do is pass json to JavaScript.
// php arrays to JSON
$behaviourLabels = json_encode($behTypes);
$behaviourValues = json_encode($behValues);
Now in javascript
var arrLables = <?php echo($behaviourLabels); ?>;
var arrValues = <?php echo($behaviourValues); ?>;
// Now use them directly in you configuration
data: {
labels: arrLables,
datasets: [{
label: "Incident Type",
backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
data: arrValues,
}]
},

Related

Using PHP and Javascript in a hybrid way, to traverse through a loop

I am trying to draw two graphs using chartjs. I want to make my life simplier by using a for loop to declare the variables required for the chart object.
The thing is I have created a 2d array, with each row storing data for current year, the next row storing data for the consecutive year and so on. I am trying to access the row of the variable using loop.
Here is my Chart obj
var canvas6= {
type: 'doughnut',
data: {
datasets: [{
data: [
<?php
for($i=0;$i<count($dataAgeGrp[1]);$i++){ -------->Note here
echo $dataAgeGrp[1][$i]; -------->And here
echo ',';
}
?>
],
backgroundColor: [
<?php
for($i=0;$i<count($ageCategory);$i++){
$rand = str_pad(dechex(rand(0, 0xFFFF00)), 6, 0, STR_PAD_LEFT);
echo('"#' . $rand.'"');
echo ",";
}
?>
],
label: 'Pie Chart'
}],
labels: [
<?php
for($i=0;$i<count($ageCategory);$i++){
echo $ageCategory[$i];
echo ',';
}
?>
],
},
options: {
responsive: true
}
};
$(function () {
var ctx126 = document.getElementById('canvas6').getContext('2d');
window.myPie = new Chart(ctx126 , canvas6);
});
So, I tried something like this
for(var k=0;k<3;k++){
var q=26;
var canvas+q = {
type: 'doughnut',
data: {
datasets: [{
data: [
<?php
for($i=0;$i<count($dataAgeGrp[k]);$i++){
echo $dataAgeGrp[k][$i];
echo ',';
}
?>
],
backgroundColor: [
<?php
for($i=0;$i<count($ageCategory);$i++){
$rand = str_pad(dechex(rand(0, 0xFFFF00)), 6, 0, STR_PAD_LEFT);
echo('"#' . $rand.'"');
echo ",";
}
?>
],
label: 'Pie Chart'
}],
labels: [
<?php
for($i=0;$i<count($ageCategory);$i++){
echo $ageCategory[$i];
echo ',';
}
?>
],
},
options: {
responsive: true
}
};
$(function () {
var ctx1+q = document.getElementById('canvas'+q).getContext('2d');
window.myPie = new Chart(ctx1+q , canvas+q);
});
q=q+1;
But I am getting this error
Use of undefined constant k - assumed 'k' (this will throw an Error in a future version of PHP)
How do I fix it?
If you can use PHP variables in your JavaScript code, the contrary is not possible. The only way to pass JavaScript variable to PHP code is by request (reload page with GET/POST parameters or AJAX request)

Bar Chart.js doesn't show values with PHP, MySQL, AJAX

I'm using Chart.js plugin to create a bar chart with sales and purchases values by year. These values are stores in mysql database and I bring it via PHP/AJAX.
HTML
<canvas id="mybarChart"></canvas>
PHP
$sql = "SELECT YEAR(date) as years, SUM(amount) AS total FROM purchases GROUP BY YEAR(date)";
$res = mysql_query($sql);
$totalpurchases = [];
$sqll = "SELECT YEAR(date) as years, SUM(amount) AS total FROM sales GROUP BY YEAR(date)";
$ress = mysql_query($sqll);
$totalsales = [];
while($row = mysql_fetch_array($res)){
$totalpurchases[] = [$row['total']];
}
while($roww = mysql_fetch_array($ress)){
$totalsales[] = [$roww['total']];
}
echo json_encode(array($totalpurchases,$totalsales));
And I made my JS code like this:
function show_chartbar(lbl01,lbl02){
var ctx = document.getElementById("mybarChart");
var mybarChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["2013", "2014", "2015", "2016", "2017"],
datasets: [{
label: '# Total Purchase',
backgroundColor: "#26B99A",
data: lbl01
}, {
label: '# Total Sales',
backgroundColor: "#03586A",
data: lbl02
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}
if ($('#mybarChart').length ){
$.ajax({
url: "scripts/values.php",
type: "GET",
dataType: "json",
success: function(resp)
{
var totpurchases = resp[0];
var totsales = resp[1];
console.log("Total Purchases: "+totpurchases);
console.log("Total Sales: "+totsales);
show_chartbar(totpurchases,totsales);
}
});
}
In console it's showing values correctly but it doesn't display in the chart:
I tried to add additional brackets in data option but it's showing the same.
UPDATE
console.dir(resp);
How can I fix it? I'd like some help.
You are creating an Array of Arrays. I believe this will fix this issue.
while($row = mysql_fetch_array($res)){
$totalpurchases[] = $row['total'];
}
while($roww = mysql_fetch_array($ress)){
$totalsales[] = $roww['total'];
}

Use a JS string variable passed in as a parameter as the value of a data parameter in chart.js?

This is the relative Javascript that is not working quite right. The parameter thisChartData is a string and it alerts just fine; it's generated by a PHP script elsewhere (but that's not important).
If I copy and paste what the alert output into the data section the chart generates fine. But for some reason I can't use the parameter name in the data section
function drawChart( thisChartData, thisChartTitle ) {
var ctx = $("#my-chart");
alert(thisChartData); // alerts-> '131', '1043', '144', '43'
//chart data
var ctxData = {
datasets: [{
data: [ thisChartData ], //using the paramter variable doesn't work
backgroundColor: [ <?php echo $bg_color_list; ?> ]
}]
};
Meanwhile the code below works fine, I need the data to be variable depending on what I pass to the function because I'm going to have several data sets I want to scroll through.
function drawChart( thisChartData, thisChartTitle ) {
var ctx = $("#my-chart");
alert(thisChartData); // alerts-> '131', '1043', '144', '43'
//chart data
var ctxData = {
datasets: [{
data: [ '131', '1043', '144', '43' ],
backgroundColor: [ <?php echo $bg_color_list; ?> ]
}]
};
data: [ thisChartData ] should just be data: thisChartData, and when you call drawChart, pass in an array. E.g.:
function drawChart( thisChartData, thisChartTitle ) {
var ctx = $("#my-chart");
//chart data
var ctxData = {
datasets: [{
data: thisChartData, // <======
backgroundColor: [ <?php echo $bg_color_list; ?> ]
}]
};
and
drawChart(['131', '1043', '144', '43'], "title");

How to read in data array return from ajax for google chart?

var e = $.ajax({
type: "POST",
url: "<?php echo $template->get_template_dir('ajax',DIR_WS_TEMPLATES, $current_page_base,'ajax'); ?>/survey_save.php",
data: str
}).done(function(data) {
alert("Survey has been saved."+data);
$('#form').hide();
$('#results').show();
// data array for google chart
var e = [["Element", "Density", { role: "style" } ],["Copper", 8.94, "#b87333"],["Silver", 10.49, "silver"],["Gold", 19.30, "gold"],["Platinum", 21.45, "color: #e5e4e2"]];
return e;
});
google.charts.load("current", {packages:['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable(e);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{ calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation" },
2]);
var options = {
title: "Density of Precious Metals, in g/cm^3",
width: 600,
height: 400,
bar: {groupWidth: "95%"},
legend: { position: "none" },
};
var chart = new google.visualization.ColumnChart(document.getElementById("columnchart_values"));
chart.draw(view, options);
}
}
So the code above will return the data array as JSON. I need to either return it as an array or convert the JSON to an array format. How could I do that? When trying to call the
Explanation:
Pass AJAX request and get response data in JSON using mysql query. Feed response data to chart function.
In short, you need to get array values -> convert into JSON and give those values to google chart irrespective whether you need mysql or not. Modify code according to your requirement.
Client side main php
<script>
drawLineChart('<?php echo strtolower($chartType); ?>');
</script>
Client side function php
function drawLineChart(chartType, chartTitle) {
google.charts.setOnLoadCallback(lineChartData);
function lineChartData() {
var lineChartJsonData = $.ajax({
type: 'GET',
url: "<?php echo $server_script_path; ?>",
data: { id1: chartType, id2: "Chart" },
dataType:"json",
async: false,
beforeSend: function() {
},
success: function(data) {
},
}).responseText;
var options;
options = {
title: chartTitle,
width: '390',
height: '300',
vAxis: {title: '<title>'},
};
var data = new google.visualization.arrayToDataTable(($.parseJSON(lineChartJsonData)));
var chart = new google.visualization.LineChart(document.getElementById(chartType));
chart.draw(data, options);
}
}
Server side php file
if ($_GET['id1'] != "" && $_GET['id2'] == "Chart") {
// Chart type
$chartType = explode('-', $_GET['id1'])[1];
$sql = "<mysql query>";
$result = mysqli_query($conn, $sql);
$table = array();
$rows = array();
$rows[] = array('<column1>', '<column2>');
while($row = mysqli_fetch_array($result)) {
$rows[] = array('<rows>', '<rows>');
}
$table = $rows;
echo json_encode($table);
}
Live chart (my array data)

How to pass nested foreach Values to CanvasJS chart?

I do some calculations with below Code and after that i want to pass the values to the Chart but i can not send them i have try this:
$getStoreIDs = mysqli_query($dbConnection, "SELECT DISTINCT Stores_storeID FROM maintable WHERE Survey_surveyId = '$surveyID' ");
while ($row = mysqli_fetch_array($getStoreIDs))
{
$storeIDarray[] = $row;
}
foreach($_POST['sections'] as $selected)
{
foreach ($storeIDarray as $key => $row)
{
$storeID = $row['Stores_storeID'];
$storeNames= mysqli_query($dbConnection , "SELECT storeName FROM stores WHERE storeID = '".$row['Stores_storeID']."'");
$sectinName = mysqli_query($dbConnection , "SELECT sectionName FROM sections WHERE sectionID = '$selected' ");
$totalSections = mysqli_query($dbConnection, "SELECT SUM(itemPrice) AS totalSection FROM maintable WHERE items_Family_Sections_sectionID='$selected' AND Stores_storeID = '$storeID' AND Survey_surveyId = '$surveyID' ");
}
}
i want to pass the values of ($storeNames, $ectionName and $totalSelections)
and here is my CanvasJs code `
var chart1 = new CanvasJS.Chart("chartContainer1",
{
title:{
text: "Store Comparision"
},
animationEnabled: true,
axisY: {
title: "Total Price"
},
legend: {
verticalAlign: "bottom",
horizontalAlign: "center"
},
theme: "theme2",
data: [
{
type: "column",
showInLegend: true,
legendMarkerColor: "grey",
dataPoints: [
]
}
]
});
chart1.render();`
First you need to put your javascript code before canvas chart,it renders.
How you are passing data to your view is important.Are you passing as json object or array?
If as json then need to parse in javscript before sending encoded in php.
In datapoints paraemeter you can pass like this
dataPoints: JSON.parse(<?php echo json_encode($json_managers) ?>)
Or can do via PHP before sending (A sample code snippet)
$managers = DB::table('orders')
->join('managers', 'orders.manager_id', '=', 'managers.id')
->groupBy('managers.manager_name')
->get(['managers.manager_name',DB::raw("sum(orders.sale) as sale")]);
foreach($managers as $key => $value){
$point = array("label" => $value->manager_name , "y" => $value->sale);
array_push($data_manager_points, $point);
}
$json_managers = json_encode($data_manager_points,JSON_NUMERIC_CHECK);
For more get here :
http://canvasjs.com/forums/topic/how-can-i-use-php-mysql-dynamic-data/

Categories