how to display three lines on chart - javascript

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

Related

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')); ?>

canvasjs showing blank, data not shown

I'm using Canvasjs to create a candlestick chart. The values are coming from PHP and I use JSON-encode to convert to the javascript array. I recreate the javascript array in the same format as the example, which is this
dataPoints=[{x: new Date(2012,01,01),y:[5198, 5629, 5159, 5385]}]
But the canvas is blank? Here is my code:
<?php
$chart_array[] = array("x"=>"2012-01-01","y"=>array("5198", "5629", "5159", "5385"));
$chart_array[] = array("x"=>"2012-01-02","y"=>array("5366", "5499", "5135", "5295"));
$chart_array = json_encode($chart_array);
?>
<script type="text/javascript">
window.onload = function () {
var resultArray = <?php echo $chart_array; ?>;
var new_array = [];
jQuery.each(resultArray, function(index, item) {
new_array.push({ x: new Date(item.x), y: item.y });
});
console.log(new_array);
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "Basic Candle Stick Chart"
},
zoomEnabled: true,
axisY: {
includeZero: false,
title: "Prices",
prefix: "$ "
},
axisX: {
interval: 2,
intervalType: "month",
valueFormatString: "MMM-YY",
},
data: [
{
type: "candlestick",
dataPoints: new_array
}
]
});
chart.render();
}
</script>
console.log show the array exists. Why is a blank canvas showing? How do I solve?
Y-value in your code seems to be string, which should be numeric. Even if you are storing it as string, parsing it to number before passing it to chart-options will work fine.
Here is the working code:
<?php
$chart_array[] = array("x"=>"2012-01-01","y"=>array(5198, 5629, 5159, 5385));
$chart_array[] = array("x"=>"2012-01-02","y"=>array(5366, 5499, 5135, 5295));
$chart_array = json_encode($chart_array);
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script type="text/javascript">
window.onload = function () {
var resultArray = <?php echo $chart_array; ?>;
var new_array = [];
jQuery.each(resultArray, function(index, item) {
new_array.push({ x: new Date(item.x), y: item.y });
});
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "Basic Candle Stick Chart"
},
zoomEnabled: true,
axisY: {
includeZero: false,
title: "Prices",
prefix: "$ "
},
axisX: {
interval: 2,
intervalType: "month",
valueFormatString: "MMM-YY",
},
data: [
{
type: "candlestick",
dataPoints: new_array
}
]
});
chart.render();
}
</script>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>

Loop inside Jquery Chart to make it dynamic

Im new in Js and Jquery and I have a curiosity about the Jquery Chart that is free to download and I want to make the data inside to be coming from the database to make it dynamic but somehow I find it difficult to loop it in.
here is my sample code, I used PHP to get the database and pass it on a JS variable
<!DOCTYPE HTML>
<html>
<head>
<?php
$link = mysqli_connect("localhost","root","","raksquad_centralized") or die("Error " . mysqli_error($link));
if($link->connect_error){
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT * FROM raksquad_centralized.grade";
$result = $link->query($query);
$subject_id= array();
$genAve = array();
while($row = mysqli_fetch_array($result)){
$subject_id[] = $row['subject_id'];
$genAve[]= $row['gen_ave'];
}
?>
<script type="text/javascript">
window.onload = function () {
var DataXAxis = <?php echo json_encode($subject_id); ?>; // X axis that corresponds to students
var DataYAxis = <?php echo json_encode($genAve); ?>; // Y axis that corresponds to grades
var chart = new CanvasJS.Chart("chartContainer",
{
title:{
text: "Top Students"
},
animationEnabled: true,
axisY: {
title: "Grades"
},
axisX: {
title: "Students"
},
legend: {
verticalAlign: "bottom",
horizontalAlign: "center"
},
theme: "theme2",
data: [
{
type: "column",
showInLegend: true,
legendMarkerColor: "grey",
legendText: "General Average",
dataPoints: [
//the area to loop with the value of DataXAxis, DataYAxis
{y: 98, label: "MT1234" },
{y: 72, label: "MT1236"} //corresponds to the barcharts
]
}
]
});
chart.render();
}
</script>
<script type="text/javascript" src="./canvasjs.min.js"></script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;">
</div>
</body>
</html>
appreciate for the help, useful for learning :)
I just use a php code to fetch the data, then json encode it.
On the script use json parse

Passing data with a search variable to Highcharts not working

As said in the title, I'm actually making a small application where you can look for a random name into a database and it shows you the adequate chart (the chart that shows the searched name's data).
It works well when I tried that by puting a static name in my data.php file (from where the chart takes the data). But when I used $_GET[ 'search' ] instead it didn't show anything. (I checked my data.php and it returns the JSON correctly) so I guess it comes from HighCharts.
Do you by chance know what could be the problem please?
Here's some parts of my code so you can understand what I'm saying.
data.php
<?php
try
{
$bdd = new PDO('mysql:host=localhost;dbname=nsui', 'root', '', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
}
catch (Exception $e)
{
die('Erreur : ' . $e->getMessage());
}
$sql=<<<SQL
SELECT `Period_start_time`, `Segment_Name`,
`csf_bh`, `drp_sd_bh`, `ec_tch_bh`, `ec_hors_cong_bh`
FROM `call_succes`
WHERE `Segment_Name`='{$search}'
SQL;
$reponse = $bdd->query($sql);
$bln = array();
$bln['name'] = 'Period_start_time';
$rows1['name']='csf_bh';
$rows2['name']='drp_sd_bh';
$rows3['name']='ec_tch_bh';
$rows4['name']='ec_hors_cong_bh';
while($donnee=$reponse->fetch()){
$bln['data'][] = $donnee['Period_start_time'];
$rows1['data'][] = $donnee['csf_bh'];
$rows2['data'][] = $donnee['drp_sd_bh'];
$rows3['data'][] = $donnee['ec_tch_bh'];
$rows4['data'][] = $donnee['ec_hors_cong_bh'];
}
$rslt = array();
array_push($rslt, $bln);
array_push($rslt, $rows1);
array_push($rslt, $rows2);
array_push($rslt, $rows3);
array_push($rslt, $rows4);
print json_encode($rslt, JSON_NUMERIC_CHECK);
$reponse->closeCursor();
?>
chart.php
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container_call',
type: 'line'
},
title: {
text: 'Call Setup Failure',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: [],
title: {
text: 'Date'
}
},
yAxis: {
labels: {
format: '{value} %'
},
min: 0,
title: {
text: 'Percentage (%)'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
valueSuffix: '%',
shared: true
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0
},
series: []
};
$.getJSON("data.php", function(json) {
options.xAxis.categories = json[0]['data']; //xAxis: {categories: []}
options.series[0] = json[1];
options.series[1] = json[2];
options.series[2] = json[3];
options.series[3] = json[4];
chart = new Highcharts.Chart(options);
});
});
</script>
In my search page I've put a code like :
<?php
...
...
global $search;
$button = $_GET [ 'submit' ];
$search = $_GET [ 'search' ];
...
...
$html.=<<<HTML
<div class="box alt">
<div class="row 50% uniform">
<div id="container_call" class="6u 6u(xsmall)">
HTML;
include ('chart.php');
$html.=<<<HTML
</div>
</div>
</div>
...
?>
And of course with the adequate javascript for highcharts etc. When I click on the button search in my home page it redirects me to my search page.
Thank you in advance.

Highcharts Dynamic Chart with MySQL Data doesn't reload

Good evening everyone,
this moment I try to work with HighChart / HighStock and after several weeks I were able to display my MySQL-data in the charts. But: I always want more.
Well, I try to reach a dynamic chart which is refreshing like the examples you may know from the website. http://jsfiddle.net/sdorzak/HsWF2/
I used the sample code as a guide. It doesn't work, but think the problem is the missing y-axis because y-axis data come from my MySQL database while x-axis should be the current time.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>POS RESULT</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
</head>
<body>
<?php
include "config.php";
$SQL1 = "SELECT * FROM Prices WHERE ticker ='FB'";
$result1 = mysql_query($SQL1);
$data1 = array();
while ($row = mysql_fetch_array($result1)) {
$data1[] = $row['Close'];
}
?>
<script type="text/javascript">
$(function () {
var chart;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'line',
marginRight: 130,
marginBottom: 25,
events: {
load: function()
{
var series = this.series[0];
setInterval(function() {
var x = (new Date()).getTime();
series.addPoint([x], true);
}, 1000);
},
title: {
text: 'Monthly Average Temperature',
x: -20 //center
},
subtitle: {
text: 'Source: WorldClimate.com',
x: -20
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
//categories: [<?php echo join(',', $data2); ?>],
},
yAxis: {
title: {
text: 'Temperature (°C)'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y +'°C';
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: [{
name: 'Tokyo',
data: [<?php echo join(',', $data1); ?>]
}]
});
});
});
</script>
<div id="container" style="min-width: 500px; height: 400px; margin: 0 auto"></div>
</body>
</html>
The passage I am talking about and which is shown in the samples is
chart: {
renderTo: 'container',
type: 'spline',
marginRight: 10,
events: {
load: function() {
// set up the updating of the chart each second
var series = this.series[0];
setInterval(function() {
var x = (new Date()).getTime(), // current time
y = Math.random();
series.addPoint([x, y], true, true);
}, 1000);
}
}
But, as I already wrote, I don't need a random y-axis, just x-axis.
Maybe you can help.
Thanks for your help.
Edit:
live-server-data.php
<?php
// Set the JSON header
header("Content-type: text/json");
include "config.php";
$SQL1 = "SELECT * FROM Prices WHERE Ticker ='TSLA'";
$result1 = mysql_query($SQL1);
while ($row = mysql_fetch_array($result1)) {
$data1[] = $row['Close'];
}
// The x value is the current JavaScript time, which is the Unix time multiplied
// by 1000.
$x = time() * 1000;
// The y value is a random number
$y = $data1;
// Create a PHP array and echo it as JSON
$ret = array($x, $y);
echo json_encode($ret);
?>
The value "Close" is decimal 24,4.
See that solution: http://www.highcharts.com/studies/live-server.htm
var chart; // global
/**
* Request data from the server, add it to the graph and set a timeout to request again
*/
function requestData() {
$.ajax({
url: 'live-server-data.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20; // shift if the series is longer than 20
// add the point
chart.series[0].addPoint(eval(point), true, shift);
// call it again after one second
setTimeout(requestData, 1000);
},
cache: false
});
}
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'spline',
events: {
load: requestData
}
},
title: {
text: 'Live random data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'Value',
margin: 80
}
},
series: [{
name: 'Random data',
data: []
}]
});
});
im trying to create another page that can relate to my bar chart. You can go through his code. It work for me
<!DOCTYPE html>
<html>
<head>
<?php
session_start();
?>
<meta charset="utf-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script>
$('#calendar').datepicker({
});
!function ($) {
$(document).on("click","ul.nav li.parent > a > span.icon", function(){
$(this).find('em:first').toggleClass("glyphicon-minus");
});
$(".sidebar span.icon").find('em:first').addClass("glyphicon-plus");
}(window.jQuery);
$(window).on('resize', function () {
if ($(window).width() > 768) $('#sidebar-collapse').collapse('show')
})
$(window).on('resize', function () {
if ($(window).width() <= 767) $('#sidebar-collapse').collapse('hide')
})
</script>
<style>
.selection{
border: 1px solid gray;
border-radius: 10px;
padding: 10px;
text-decoration:none;
float:left;
margin:4px;
text-align:center;
display: block;
color: green;
}
.page-header{
text-align:center;
text-decoration:hover;
color: blue;
font-size: 30px;
}
</style>
<script>
$(function () {
//on page load
getAjaxData(1);
//on changing select option
$('#dynamic_data').change(function(){
var val = $('#dynamic_data').val();
getAjaxData(val);
});
function getAjaxData(id){
//use getJSON to get the dynamic data via AJAX call
$.getJSON('datab1.php', {id: id}, function(chartData) {
$('#container').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Analysis of Data Type in The World'
},
xAxis: {
categories: ['Population', 'Health', 'Agriculture', 'Development', 'Transport', 'Education', 'Social', 'Tourism', 'Finance','Business','Economy', 'Industry', 'Employment', 'Weather', 'Food', 'Energy', 'Infrastructure', 'Science&Technology', 'Government','Culture', 'Religion',
'Justice&Law', 'Country', 'Water Resource', 'Maritim', 'Military', 'International', 'Geography', 'Statistics', 'Others','Electronic','Biotechnology', 'Women', 'Gender', 'Cartography','Disability','Position','Marital','CDF','Research']
},
yAxis: {
min: 0,
title: {
text: 'Percentage (%)'
}
},
legend: {
enabled: false
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
'<td style="padding:0"><b>{point.y:.1f} %</b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: chartData
});
});
}
});
</script>
</head>
<body class="hold-transition skin-blue sidebar-mini">
<div id="container" style="width: 100%; min-height: 500px; margin: 0 auto"></div>
</body>
</html>
And this the code for fetching data from mysql
<?php
require('dbcon.php');
//select database
//define array
//we need two arrays - "male" and "female" so $arr and $arr1 respectively!
$arr = array();
$result = array();
//get the result from the table "highcharts_data"
$sql = "select * from world";
$q = mysqli_query($con, $sql) or die(mysqli_error());
$j = 0;
while ($row = mysqli_fetch_assoc($q)) {
//highcharts needs name, but only once, so give a IF condition
if ($j == 0) {
$arr['name'] = 'Percentage';
$j++;
}
//and the data for male and female is here
$arr['data'][] = $row['datavalue'];
}
//after get the data for male and female, push both of them to an another array called result
array_push($result, $arr); //1
//now create the json result using "json_encode"
print json_encode($result, JSON_NUMERIC_CHECK);
mysqli_close($con);
?>

Categories