php database to javascript chart - javascript

How to replace my javascript datapoints to my mysql database?
My array x and y ??? i have trouble in plotting my mysql database...
ex.
array("x" =>(HERE), "y" =>HERE),
by database $row['year'];
<?php
$dataPoints = array(
array("x" => 946665000000, "y" => 40),
array("x" => 978287400000, "y" => 20),
array("x" => 1009823400000, "y" => 100),
array("x" => 1041359400000, "y" => 300),
array("x" => 1072895400000, "y" => 500),
array("x" => 1104517800000, "y" => 500),
array("x" => 1136053800000, "y" => 400),
array("x" => 1167589800000, "y" => 400),
);
?>
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
<script>
window.onload = function () {
var chart1 = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
title:{
text: "Number of Enrollees by Year"
},
axisY: {
title: "Students in numbers",
valueFormatString: "#",
suffix: "",
prefix: ""
},
data: [{
type: "spline",
markerSize: 5,
xValueFormatString: "YYYY",
yValueFormatString: "##0. Enrolees",
xValueType: "dateTime",
dataPoints: <?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
}]
});
chart1.render();
}
</script>
Its just a template from chartjs.com
Please help me guys form database php to javascript...

As easy as :
array_walk($dataPoints, function (&$dp, $index) use($show) {
$dp['y'] = $show['table_data'][$index]['y'];
})
I hope to help you.

Related

how to display three lines on chart

I create a chart using canvasjs. Values display in chart is from mysql database. All working but the problem is, it showing just 1 line on chart (sensors_pres) from table SensorData on chart not all three sensors_pres, sensors_temperature_data and sensors_humidity.
Other problem is on range slider is not showing hour from 0 to 24, test it. Click in left-up on button all and in right-up you will see the number -1 to 96. How can i solve?
I opened data.php file with browser and all values working correct.
Here is my html&javascript code
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.stock.min.js"></script>
<script type="text/javascript">
window.onload = function () {
$.getJSON("data.php", function (result) {
var stockChart = new CanvasJS.StockChart("chartContainer",{
title:{
text:"StockChart with Numeric Axis"
},
animationEnabled: true,
exportEnabled: true,
charts: [{
axisX: {
crosshair: {
enabled: true,
snapToDataPoint: true
}
},
axisY: {
crosshair: {
enabled: true,
//snapToDataPoint: true
}
},
data: [{
type: "line",
dataPoints: result
}]
}],
rangeSelector: {
inputFields: {
startValue: 00,
endValue: 24,
valueFormatString: "###0"
},
buttons: [{
label: "00",
range: 00,
rangeType: "number"
},{
label: "12",
range: 12,
rangeType: "number"
},{
label: "24",
range: 24,
rangeType: "number"
},{
label: "All",
rangeType: "all"
}]
}
});
stockChart.render();
})
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 450px; width: 100%;"></div>
</body>
</html>
here is my php code:
<?php
header('Content-Type: application/json');
$con = mysqli_connect("fdb30.awardspace.net","3758712_lnd","bogdanutzu97","3758712_lnd");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to DataBase: " . mysqli_connect_error();
}else
{
$data_points = array();
$result = mysqli_query($con, "SELECT * FROM SensorData");
while($row = mysqli_fetch_array($result))
{
$point = array("label" => $row['reading_time'] , "y" => $row['sensors_pres'],$row['sensors_temperature_data'],$row['sensors_humidity']);
array_push($data_points, $point);
}
echo json_encode($data_points, JSON_NUMERIC_CHECK);
}
mysqli_close($con);
?>
data: [
{
type: "line",
dataPoints: result1
},
{
type: "line",
dataPoints: result2
},
{
type: "line",
dataPoints: result3
}
]
In your data section add 2 more data sets

Chart.js process data in server-side before show to chart

i want to process generated Eloquent result data in server side before show it to Chart.js, all the data are dynamically generated from databases.
I've facing some issue while try to increment subtotal values for the same items_name and sales_date and then show labels, x & y axis from database.
Here's my Eloquent ->toArray() response :
array:5 [
0 => array:3 [
"sales_date" => "2021-02-25"
"subtotal" => 800000
"items_name" => "Kitchen Set"
],
1 => array:3 [
"sales_date" => "2021-02-25"
"subtotal" => 2000000
"items_name" => "Kitchen Set"
],
2 => array:3 [
"sales_date" => "2021-02-26"
"subtotal" => 1000000
"items_name" => "Chair"
],
3 => array:3 [
"sales_date" => "2021-02-26"
"subtotal" => 1000000
"items_name" => "Chair"
],
4 => array:3 [
"sales_date" => "2021-02-27"
"subtotal" => 1000000
"items_name" => "Stove"
],
]
I also tried to use ->map() function in server side :
$processed['labels'] = [];
$results->map( function( $val, $key ) use(&$processed) {
$processed['labels'][$key] = $val->sales_date;
if( $processed['labels'][$key] === $val->sales_date) {
$processed['datas'][$key] = ["data" => $val->subtotal, "label" => $val->varieties_name];
}
});
but i confused about the required data structure for Chart.js and show "0" sales like Google Analytics chart if there's no visitor like this image below :
Here's some expected result in Chart.js (the x axis should same from the datasets) :
This is my hardcoded Chart.js
$.ajax({
url : "{{ route('home.selling') }}",
type : "GET",
success : function( res ){
var selling_chart = new Chart(document.getElementById("selling_per_items"), {
type: 'line',
data: {
labels: ['2021-02-24', '2021-02-25', '2021-02-26', '2021-02-27'],
datasets: [{
data : [ '2800000' ],
label : 'Kitchen Set',
lineTension: 0,
fill : false,
borderColor : dynamicColors(),
},{
data : [ '2000000' ],
label : 'Chair',
lineTension: 0,
fill : false,
borderColor : dynamicColors(),
},{
data : [ '100000' ],
label : 'Stove',
lineTension: 0,
fill : false,
borderColor : dynamicColors(),
}]
},
options: {
title: {
display: false
},
responsive: true,
maintainAspectRatio : false,
},
scales: {
xAxes: [{
stacked: true,
}],
yAxes: [{
stacked: true,
ticks: {
beginAtZero: true
}
}]
}
});
}
});
My environment :
jQuery : v3.4.1
Chart.js : v2.8.0
Laravel : 8.x
Thank You

CanvasJS and PHP

I want to create two charts with CanvasJS in which I use values from php file.
I have two charts but only one renders, the second one has only white background and title text.
Here's php code with values:
<?php
require 'excCon.php';
$dataPoints = array(
array("y" => $excel_result, "label" => "Quantity"),
array("y" => $excel_result2, "label" => "Value"),
);
$dataP = array(
array("y" => $excel_result3, "name" => "1", "exploded" => false),
array("y" => $excel_result4, "name" => "2"),
array("y" => $excel_result5, "name" => "3&5"),
array("y" => $excel_result6, "name" => "4"),
);
?>
and javascript:
<div id="chartContainer style="height: 400px;width: 80%"">
<script type="text/javascript">
$(function () {
var chart1 = new CanvasJS.Chart("chartContainer", {
theme: "theme2",
animationEnabled: true,
title: {
text: "Sum"
},
data: [
{
type: "column",
dataPoints: <?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
}
]
});
chart1.render();
});
</script>
</div>
<div id="chartContainer2" style="height: 400px;width: 80%">
<script type="text/javascript">
$(function () {
var chart2 = new CanvasJS.Chart("chartContainer2",
{
theme: "theme2",
title:{
text: "All"
},
exportFileName: "All",
exportEnabled: false,
animationEnabled: false,
data: [
{
type: "pie",
showInLegend: true,
toolTipContent: "{name}: <strong>{y}%</strong>",
indexLabel: "{name} {y}%",
dataP: <?php echo json_encode($dataP, JSON_NUMERIC_CHECK); ?>
}]
});
chart2.render();
});
</script>
</div>
The whole code is in index.php file.
For the record, I searched other solutions here as well as on the official page and none worked.
Solution is to have dataPoints in data and do not change it
data: [
{
type: "column",
**dataPoints** : <?php echo json_encode($dataP, JSON_NUMERIC_CHECK); ?>

JavaScript does not echo values coming from database

The first thing I get values from database with no problem. Then I can echo the values but after The values turn in to null. Somehow the values do not pass this point. Here are my codes.
php and mysql part
$rows = array();
$result = mysql_query("SELECT * FROM kayitlar");
$i=1;
while($row = mysql_fetch_array($result)) {
$rows []= array(
'id' => $row['id'],
'ad' => $row['ad'],
'saat' => $row['saat'],
);
$i++;
}
No problem till this point. Here is the rest of the code that I am having problem
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer",
{
title:{
text: "title"
},
animationEnabled: true,
axisY: {
title: "Zaman (saat)"
},
legend: {
verticalAlign: "bottom",
horizontalAlign: "center"
},
theme: "theme2",
data: [
{
type: "column",
showInLegend: true,
legendMarkerColor: "grey",
legendText: "saat",
dataPoints: [
{y:<?php echo json_encode($row['ad']); ?>, label: "<?php echo json_encode($row['saat']); ?> "},
]
}
]
});
chart.render();
}
</script>
here where I stuck <?php echo json_encode($row['ad']); ?> is getting no value
Your $rows array indexed array which contain your keys in every index. So you need to extract your keys value pair from array.
After your while loop completed, add following codes
$arr['ad'] = array_column($rows,"ad");
$arr['saat'] = array_column($rows,"saat");
$arr['id'] = array_column($rows,"id");
Now use this in your jS
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer",
{
title:{
text: "title"
},
animationEnabled: true,
axisY: {
title: "Zaman (saat)"
},
legend: {
verticalAlign: "bottom",
horizontalAlign: "center"
},
theme: "theme2",
data: [
{
type: "column",
showInLegend: true,
legendMarkerColor: "grey",
legendText: "saat",
dataPoints: [
{y:<?php echo json_encode($arr['ad']); ?>, label: "<?php echo json_encode($arr['saat']); ?> "},
]
}
]
});
chart.render();
}
</script>
Your array is multidimensional array so simple use array_column to get specific column value from each index and apply json_encode()
<?php echo json_encode(array_column($rows,'ad')); ?>
<?php echo json_encode(array_column($rows,'saat')); ?>

Google chart timeline with date in x axis

Working on a google line chart. The problem I have came into is that the chart on shows values of one day, have not implemented timeline with dates. I understand that the chart will be wide if your getting values from for example one week, is there any way to solve that ? I was thinking of something like this ?
How its looking right now:
Database: ( the date is saved as date in phpadmin)
Code:
<?php
$con=mysql_connect("localhost","root","") or die("Failed to connect with database!!!!");
mysql_select_db("chart", $con);
$sth = mysql_query("SELECT * FROM googlechart");
$rows = array();
//flag is not needed
$flag = true;
$table = array();
$table['cols'] = array(
// Labels for your chart, these represent the column titles
// Note that one column is in "string" format and another one is in "number" format as pie chart only required "numbers" for calculating percentage and string will be used for column title
array('label' => 'Time', 'type' => 'number'),
array('label' => 'PH', 'type' => 'number'),
array('label' => 'temperature','type' => 'number'),
array('label' => 'Chlorine','type' => 'number'),
);
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$temp = array();
$temp[] = array('v' => (string) $r['Time']);
$temp[] = array('v' => (string) $r['PH']);
$temp[] = array('v' => (string) $r['temperature']);
$temp[] = array('v' => (string) $r['Chlorine']);
$temp[] = array('v' => (int) $r['Time']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
echo $jsonTable;
?>
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable(<?=$jsonTable?>);
var options = {
/*width: 900, height: 900, */
title: 'Visualization',
/* curveType: 'function', */
legend: { position: 'bottom' },
pointSize: 10,
vAxis: {title: "Values", titleTextStyle: {italic: false}},
hAxis: {title: "Time", titleTextStyle: {italic: false}},
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
You can get part of what you want using format property of hAxis, for example:
hAxis: {
format: "HH:mm",
...
}
See line chart configuration options for hAxis.format.
Update: Example at jsbin

Categories