Dynamic Chart in PHP using Chart js - javascript

I am not being able to show the values from my PHP file into my HTML file using Chart js. I am trying to import it through AJAX request. I tried it through printing the database value as JSON in the PHP file. The encoding worked well but I can't show them in graph for some reason. Please suggest any other way if possible to do the task mentioned in the code
HTML:
<html>
<head>
<meta charset="utf-8"/>
<title>Chart.js demo</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/0.2.0/Chart.min.js" type="text/javascript"></script>
<script src="assets/js/jquery.min.js" type="text/javascript"></script>
<script src="assets/js/LineGraph.js" type="text/javascript" ></script>
</head>
<body>
<h1>Chart.js Sample</h1>
<div id= "graphDiv" style="width:100%; height:auto;">
</div>
<script>
showGraph();
function showGraph(){
$.post("agSensorInterfaceUpdate.php", function (data){
console.log(data);
var ctx = $("#graphCanvas");
var acc_data = [];
var gyr_data = [];
var serial = [];
for(var i in data) {
acc_data.push(data[i].accelerometer);
gyr_data.push(data[i].gyroscope);
serial.push(data[i].serial_no);
}
var chartdata = {
labels: serial_no,
datasets: [
{
label: 'Accelerometer Data',
backgroundColor: 'rgba(200,200,0.75)',
borderColor: 'rgba(200,200,0.75)',
hoverBackgroundColor: 'rgba(200,200,200,1)',
hoverBorderColor: 'rgba(200,200,200,1)',
data: acc_data
}
]
};
var lineGraph = new Chart(ctx, {
type:'line',
data: chartdata
});
});
}
</script>
</body>
PHP:
<?php
header('Content-Type: application/json');
$username = "root";
$password = "";
$database = "arthor_bb";
$serial=1;
$sensor_value = array();
$mysqli = new mysqli("localhost", $username, $password, $database);
$query = "SELECT * FROM `sensor_data`";
$result = $mysqli->query($query);
foreach ($result as $row){
$sensor_value[] = $row;
}
$result -> close();
print json_encode($sensor_value);
?>

your "graphDiv" html element needs to be a canvas. not a div.
<canvas id="myChart" width="100%" height="50%"></canvas>
You also have the wrong id on your ctx variable.
let ctx = document.getElementById('myChart').getContext('2d'); // canvas

Related

Google chart bug when using PDO connection

I'm trying to use google charts to show my database values. I'm using PDO for my database queries inside a class where I instantiate it as an object on my HTML page inside my PHP tag. However the google chart is not working the way it should be, the piechart title and the names of the values are not showing up.
This is my current output
This is what I want to be shown
my html page:
<?php
$dashboard = new userview; ?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript"
src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['ticketstatus', 'statusnumber'],
<?php
$dashboard->getstatuscount();
?>
]);
var options = {
title: 'Request Status'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="piechart" style="width: 900px; height: 500px;">
</div>
</body>
</html>
my query class :
class userview extends dbh{
public function getstatuscount() {
$sql = "SELECT ticketstatus, COUNT(*) as statusnumber FROM ticketpractice GROUP BY ticketstatus";
$result = $this->connect()->query($sql);
while ($row = $result->fetch()) {
echo "['".$row['ticketstatus']."',".$row['statusnumber']."]," ;
}
}
}
my database class
class dbh
{
private $dbhost = "localhost";
private $dbusername = "root";
private $dbpassword = "";
private $dbname = "myphplessons";
protected function connect () {
$dsn = 'mysql:host=' . $this->dbhost . ';dbname=' . $this->dbname;
$pdo = new PDO ($dsn,$this->dbusername, $this->dbpassword);
$pdo->setAttribute (PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
return $pdo;
}
}

How do I create a C3 Chart Line Graph from JSON data?

I need help for a school project. I have been able to pull data from a mySQL database into an array and encoded into JSON, which displays fine. Now, I need help with passing the JSON data to C3 to produce a chart (if possible on the same page).
What I've done so far:
$strQuery = "SELECT production_date,oil FROM production WHERE well = '$h_well' AND production_date BETWEEN '$h_start' AND '$h_end' ORDER BY production_date ASC";
$result = mysqli_query($conn, $strQuery);
// Print out rows
$data = array();
while ( $row = $result->fetch_assoc() ) {
$data[] = $row;
}
echo json_encode( $data );
You need to create two separate array, one for your data and one for dates that you want to show on x-axis and then pass that array to java script.
here is full working example
<?php
$conn = mysqli_connect("localhost", "root", "", "test_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$strQuery = "SELECT production_date,oil FROM production WHERE well = '$h_well' AND production_date BETWEEN '$h_start' AND '$h_end' ORDER BY production_date ASC";
$result = mysqli_query($conn, $strQuery);
// Print out rows
$valuesArray = array();
$datesArray = array();
$valuesArray[] = 'Oil';
$datesArray[] = 'x';
while ($row = $result->fetch_assoc()) {
$datesArray[] = $row['production_date'];
$valuesArray[] = $row['oil'];
}
?>
<html>
<head>
<title>C3 Liner example</title>
<link href="c3_scr/c3.css" rel="stylesheet" type="text/css" />
<script src="https://d3js.org/d3.v3.min.js"></script>
<script src="c3_scr/c3.js"></script><!-- load jquery -->
</head>
<body>
<div id="chart"></div>
<script>
var xAxisArr = <?php echo json_encode($datesArray); ?>;
var dataArr = <?php echo json_encode($valuesArray, JSON_NUMERIC_CHECK); ?>;
var chart = c3.generate({
bindto: '#chart',
data: {
x: 'x',
columns: [
xAxisArr,
dataArr
]
},
axis: {
x: {
type: 'timeseries',
tick: {
format: '%Y-%m-%d'
}
}
}
});
</script>
</body>
</html>

HighCharts and PHP json_encode. Data from MySQL. No data on chart

Trying to produce HighCharts with data from MySQL. Parsing data from MySQL using PHP and the json_encode function. Problem: No data on chart.
This is my javascript:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<style type="text/css">
</style>
<script type="text/javascript">
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'spline'
},
series: [{}]
};
$.getJSON('json.php', function(data) {
options.series[0].data = data;
var chart = new Highcharts.Chart(options);
});
});
</script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
</head>
<body>
<div id="container" style="max-width: 500px; height: 400px; margin: 0 auto"></div>
</body>
</html>
This is my json.php:
<?php
$host = "localhost:3306";
$user = "removed";
$pass = "removed";
$dbname = "removed";
$connection = mysqli_connect($host, $user, $pass, $dbname);
$query = "SELECT temp, time from vejr where time > '2016-04-25 06:14:23'";
$result = mysqli_query($connection, $query);
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode($emparray);
?>
This is the output from the json.php:
[{"temp":"1.6","time":"2016-04-25 08:14:23"}, {"temp":"2.6","time":"2016-04-25 09:14:23"},{"temp":"3.6","time":"2016-04-25 10:14:23"},{"temp":"4.6","time":"2016-04-25 11:14:23"}, {"temp":"5.6","time":"2016-04-25 12:14:23"},{"temp":"6.6","time":"2016-04-25 13:14:23"},{"temp":"7.6","time":"2016-04-25 14:14:23"},{"temp":"8.6","time":"2016-04-25 15:14:23"}]
What I'm trying to do is a chart with time (fx 2016-04-25 08:14:23) on the x-axis, and the value (fx 1.6) on the y-axis.
Got inspiration from this: http://www.highcharts.com/docs/working-with-data/custom-preprocessing#3
And also, I know that my timestamp on the x-axis is not perfect, it is long (2016-04-25 08:14:23), but that is what my feeding-software currently is sending to my MySQL. What would be perfect?
Kind Regards
The issue is caused by 3 reasons.
Values should be named like x and y, not custom fields
The y value should be number, not string like you have (use the JSON_NUMERIC_CHECK flag in json_encode)
The x value, should be timestamp (time in miliseconds). In PHP you can use strtotime() function

CanvasJs dynamic Data with PHP, mySQL

screen shoot
Hello i have obstacle for my chart from CanvasJs.
I just put simple code to get simple chart with parameter target and actual, i found error in dataPoints: i think the problem just wrong statements.
this my error code:
dataPoints: [
<?PHP $mkmi3= mysql_query("SELECT * FROM monthkpimontindv WHERE idKpiDetIndv='$q'");
While ($mkmi4= mysql_fetch_assoc($mkmi3))
{
echo "{ label: ".$mkmi4['period'].", y: ".$mkmi4['actual']." },\n";
}
?>
]
Here is how we can display MySQL data in CanvasJS, Try like this.
Here, Create a PHP service that returns data in JSON format. HTML page that does AJAX request to the server and fetches the data. After getting the data, it renders a Chart.
PHP Service to return JSON Data
<?php
header('Content-Type: application/json');
$con = mysqli_connect("127.0.0.1","user","password","canvasjssampledb");
// 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 sales");
while($row = mysqli_fetch_array($result))
{
$point = array("label" => $row['product'] , "y" => $row['total_sales']);
array_push($data_points, $point);
}
echo json_encode($data_points, JSON_NUMERIC_CHECK);
}
mysqli_close($con);
?>
HTML Page to Fetch Data and render Chart
!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title></title>
<script src="jquery.js"></script>
<script src="canvasjs.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("data.php", function (result) {
var chart = new CanvasJS.Chart("chartContainer", {
data: [
{
dataPoints: result
}
]
});
chart.render();
});
});
</script>
</head>
<body>
<div id="chartContainer" style="width: 800px; height: 380px;"></div>
</body>
</html>
Note:: IE8- is supported in v1.3 and above.

Graph Representation of data using PHP and JavaScript

Hello there I need to represent data in graph form(chart form). For this I am using a jQuery plugin .The problem I am having is when I do this using PHP array its not working for me.
The code I am using is here.
<html>
<head>
<title>JSChart</title>
<script type="text/javascript" src="../../../sources/jscharts.js"></script>
</head>
<body>
<div id="graph">Loading graph...</div>
<?php
$phpArray = array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
$aa= json_encode($phpArray);
?>
<script type="text/javascript">
var myData = <?php echo $aa; ?>;
alert(myData);
var colors = ['#AF0202', '#EC7A00', '#FCD200', '#81C714'];
var myChart = new JSChart('graph', 'bar');
myChart.setDataArray(myData);
myChart.colorizeBars(colors);
myChart.setTitle('Year-to-year growth in home broadband penetration in U.S.');
myChart.setTitleColor('#8E8E8E');
myChart.setAxisNameX('');
myChart.setAxisNameY('%');
myChart.setAxisColor('#C4C4C4');
myChart.setAxisNameFontSize(16);
myChart.setAxisNameColor('#999');
myChart.setAxisValuesColor('#7E7E7E');
myChart.setBarValuesColor('#7E7E7E');
myChart.setAxisPaddingTop(60);
myChart.setAxisPaddingRight(140);
myChart.setAxisPaddingLeft(150);
myChart.setAxisPaddingBottom(40);
myChart.setTextPaddingLeft(105);
myChart.setTitleFontSize(11);
myChart.setBarBorderWidth(1);
myChart.setBarBorderColor('#C4C4C4');
myChart.setBarSpacingRatio(50);
myChart.setGrid(false);
myChart.setSize(616, 321);
myChart.setBackgroundImage('chart_bg.jpg');
myChart.draw();
</script>
</body>
</html>
And the below code is running perfectly.(with javascript array)
<script type="text/javascript">
var myData = new Array(['Mar04-Mar05', 21], ['Mar05-Mar06', 28], ['Mar06-Mar07', 12], ['Mar07-Mar08', 17]);
alert(myData);
var colors = ['#AF0202', '#EC7A00', '#FCD200', '#81C714'];
var myChart = new JSChart('graph', 'bar');
myChart.setDataArray(myData);
myChart.colorizeBars(colors);
myChart.setTitle('Year-to-year growth in home broadband penetration in U.S.');
myChart.setTitleColor('#8E8E8E');
myChart.setAxisNameX('');
myChart.setAxisNameY('%');
myChart.setAxisColor('#C4C4C4');
myChart.setAxisNameFontSize(16);
myChart.setAxisNameColor('#999');
myChart.setAxisValuesColor('#7E7E7E');
myChart.setBarValuesColor('#7E7E7E');
myChart.setAxisPaddingTop(60);
myChart.setAxisPaddingRight(140);
myChart.setAxisPaddingLeft(150);
myChart.setAxisPaddingBottom(40);
myChart.setTextPaddingLeft(105);
myChart.setTitleFontSize(11);
myChart.setBarBorderWidth(1);
myChart.setBarBorderColor('#C4C4C4');
myChart.setBarSpacingRatio(50);
myChart.setGrid(false);
myChart.setSize(616, 321);
myChart.setBackgroundImage('chart_bg.jpg');
myChart.draw();
</script>
</body>
</html>
The chart object is expecting a 2D array (an array inside an array).
If you look in the HTML source you will see that json_encode is giving you an object, which would look something like this:
{"Peter", "35", "Ben", "37", "Joe", "43"}
try using this:
function create_2d_array($array) {
if (count($array) == 0)
return "[]";
$results = "[";
foreach ($array as $key => $value) {
$results .= "[\"$key\", $value], ";
}
$results = substr($results, 0, strlen($results) - 2);
return $results . "]";
}
and in the javascript area:
var myData = <?php echo create_2d_array($phpArray) . ';'; ?>;

Categories

Resources