Problem to plot data from external json file into highchart? - php
I extract data from my mysqli db into JSON file like this.:
<?php
session_start();
include_once("../config.php");
$Name13 = $_SESSION['RNaam'];
$conn = new mysqli($servername ,$username, $password, $db);
$sqli = "SELECT * FROM metingen where Id > '20000' and Lijn ='Lijn 2' and FlakeType1 ='FLK PE DSD329 0216 P2S2' AND KleurL BETWEEN '60'AND '80' ORDER BY Id asc";
$result2 = mysqli_query($conn, $sqli);
//$rows = array();
$rows['metingen'] = 'metingen';
$rows['Datum'] = 'Datum';
while($r1 = mysqli_fetch_array($result2)) {
$rows['data'][] = $r1['Datum'];
$rows['data'][] = $r1['KleurL'];
}
$result2 = array();
//array_push($result2,$data);
array_push($result2,$rows);
print json_encode($result2, JSON_NUMERIC_CHECK);
$conn->close();
?>```
The result of my JSON looks like this.:
[{"metingen":"metingen","Datum":"Datum","data":["17-1-2022",77.42,"17-1-2022",77.46,"17-1-2022",75.71,"17-1-2022",78.37,"18-1-2022",78.86,"18-1-2022",78.41,"18-1-2022",76.51,"18-1-2022",76.03,"18-1-2022",75.48,"18-1-2022",75.6,"18-1-2022",75.25,"18-1-2022",76.53,"18-1-2022",78.01,"18-1-2022",77.63,"18-1-2022",78.51,"18-1-2022",78.67,"19-1-2022",76.16,"19-1-2022",75.38,"19-1-2022",75.55,"19-1-2022",73.71,"19-1-2022",76.91,"19-1-2022",77.25,"19-1-2022",78,"19-1-2022",77.81,"19-1-2022",77.65,"22-1-2022",77.21,"22-1-2022",76.97,"22-1-2022",77.43,"22-1-2022",78.08,"22-1-2022",75.76,"22-1-2022",76.12,"23-1-2022",76.07,"23-1-2022",76.32,"23-1-2022",77.43,"23-1-2022",77.97,"23-1-2022",78.03,"23-1-2022",77.86,"23-1-2022",76.41,"23-1-2022",76.69,"23-1-2022",76.44,"23-1-2022",76.4,"24-1-2022",76.2,"24-1-2022",75.97,"24-1-2022",76.85,"24-1-2022",76.2,"24-1-2022",77.56,"1-2-2022",74.88.......```
The page with highcharts looks like this.:
<!DOCTYPE HTML>
<?php
session_start();
?>
<script>
window.onload = function() {
if(!window.location.hash) {
window.location = window.location + '#loaded';
window.location.reload();
}
}
</script>
<html>
<head>
<?php
echo '<!-- <meta http-Equiv="Cache-Control" Content="no-cache"> -->';
echo '<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">';
echo '<meta http-Equiv="Pragma" Content="no-cache">';
echo '<meta http-Equiv="Expires" Content="0">';
?>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Grafiek</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/data.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<script src="https://code.highcharts.com/stock/modules/export-data.js"></script>
<script src="https://code.highcharts.com/modules/accessibility.js"></script>
<script type="text/javascript">
$(function () {
var chart;
$(document).ready(function() {
$.getJSON("datatest01112022.php", function(json) {
/*options.series[0].name = json[0]['Reg_sample'];
options.series[0].data = json[0]['KleurL'];*/
chart = new Highcharts.Chart({
chart: {
renderTo: 'container2',
type: 'line',
marginRight: 130,
marginBottom: 100
},
title: {
text: 'Gemeten L* waarde van Prep 2 bij Extrusie 2',
x: -20 //center
},
subtitle: {text: '',x: -20},
xAxis: { title: {
text: 'Datum'
}},
yAxis: {
title: {
text: 'KleurL'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
//return '<b>'+ this.series.name +'</b><br/>'+
return '<b>Meetwaarden</b><br/>'+
this.x +': '+ this.y;
}
},
legend: {layout: 'vertical',align: 'right',verticalAlign: 'top',x: -10,y: 100,borderWidth: 0},
yAxis: {
plotLines: [{value: 70,color: 'red',dashStyle: 'longdashdot',width: 2,label: {text: 'Minimum'}},
{value: 80,color: 'red',dashStyle: 'longdashdot',width: 2,label: {text: 'Maximum'}},
{value: 75,color: 'green',dashStyle: 'shortdash',width: 2,label: {text: 'Richtlijn' },
}]
},
series: json,
});
});
});
});
</script>
</head>
<body>
<div id="container2" style="min-width: 400px; height: 400px; margin: 0 auto"> </div>
<!--<script src="highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>-->
</body>
</html>```
Why dosn't plot the highcharts the values and put the date/time into the x-axis in the line, but if i remove the date/time from my JSON file it works?
Can anybody solve my problem?
You need to adapt your data to the format required by Highcharts. In your case, it can be an array of arrays, each with two values.
data: [
[0, 1],
[1, 2],
[2, 8]
]
You should do that in your php script, but you can also use JS part:
const processedData = [];
for (let i = 0; i < json[0].data.length; i += 2) {
processedData.push([json[0].data[i], json[0].data[i + 1]]);
}
json[0].data = processedData;
Live demo: http://jsfiddle.net/BlackLabel/35cem86h/
API Reference: https://api.highcharts.com/highcharts/series.line.data
Related
Not able to display barchart using chart.js and jquery in php program
I am using chart.js in php program to print chart using jquery but not able to display chart I have also included bootstrap files in my original code <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.css"> <meta charset="UTF-8"> <title>Document</title> </head> <body> <div style="width: 400px;height:400px;"> <canvas id="myChart" width="400" height="400" style="color: red;"></canvas> </div> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.js"></script> <script> $(document).ready(function(){ var data1 = { labels: ['January', 'February', 'March', 'April', 'May', 'June'], datasets: [{ label: 'My First dataset', backgroundColor: '#16a085', data: [10, 5, 2, 20, 30, 45] }] }; var options1 = { scales: { yAxes: [{ ticks: { beginAtZero: true } }] } }; var ctx = $('#myChart'); var piechart = new Chart(ctx).Bar(data1,options1); }); </script> </body> </html> Not able to display graph using var piechart = new Chart(ctx).Bar(data1,options1); but i can display chart using var piechart = new Chart(ctx,{ type:'bar', data:data1 , options: options1, }); But I want to display chart using 1st method
charts.js - json output to graph
I want to dispay in a bar graph the days and the quantity. I have following json output.(data.php) for each day the quantity. [{"day":"2017-11-15","quantity":"72"},{"day":"2017-11-16","quantity":"157"},{"day":"2017-11-17","quantity":"130"},{"day":"2017-11-18","quantity":"91"},{"day":"2017-11-19","quantity":"96"}] output.html <!DOCTYPE html> <html> <head> <title>ChartJS - BarGraph</title> <style type="text/css"> #chart-container { width: 640px; height: auto; } </style> </head> <body> <div id="chart-container"> <canvas id="mycanvas"></canvas> </div> <!-- javascript --> <script type="text/javascript" src="js/jquery.min.js"></script> <script type="text/javascript" src="js/Chart.min.js"></script> <script type="text/javascript" src="js/app.js"></script> </body> and thats the app.js $(document).ready(function(){ $.ajax({ url: "data.php", method: "GET", success: function(data) { console.log(data); var day = []; var quantity = []; for(var i in data) { day.push(data[i].day); quantity.push(data[i].quantity); } var chartdata = { labels: day, datasets : [ { label: 'DAYS', backgroundColor: 'rgba(200, 200, 200, 0.75)', borderColor: 'rgba(200, 200, 200, 0.75)', hoverBackgroundColor: 'rgba(200, 200, 200, 1)', hoverBorderColor: 'rgba(200, 200, 200, 1)', data: quantity } ] }; var ctx = $("#mycanvas"); var barGraph = new Chart(ctx, { type: 'bar', data: chartdata }); }, error: function(data) { console.log(data); } }); }); but it's always empty. but why? Any idea? Also instead of the day theres only undefined on the bottom line.
Here is the main idea data.forEach(function(packet) { labelsData.push(packet.day); datasetData.push(parseFloat(packet.quantity)); }); for example var dataJSON = [{ "day": "2017-11-15", "quantity": "72" }, { "day": "2017-11-16", "quantity": "157" }, { "day": "2017-11-17", "quantity": "130" }, { "day": "2017-11-18", "quantity": "91" }, { "day": "2017-11-19", "quantity": "96" }]; var labelsData = []; var datasetData = []; dataJSON.forEach(function(packet) { labelsData.push(packet.day); datasetData.push(parseFloat(packet.quantity)); }); var chartdata = { type: 'bar', data: { labels: labelsData, datasets: [{ label: 'DAYS', data: datasetData }] } } Working JSFiddle https://jsfiddle.net/4v3nt7sL/1/
no plan why it's empty for me.. my database output is correct it think! data.php [{"day":"15","quantity":"72"},{"day":"16","quantity":"157"},{"day":"17","quantity":"130"},{"day":"18","quantity":"91"},{"day":"19","quantity":"96"},{"day":"20","quantity":"129"},{"day":"21","quantity":"140"},{"day":"22","quantity":"141"}] index.html <!DOCTYPE html> <html> <head> <title>a simple chart</title> <style type="text/css"> #chart-container { width: 640px; height: auto; } </style> </head> <body> <div id="chart-container"> <canvas id="mycanvas"></canvas> </div> <!-- javascript --> <script type="text/javascript" src="js/jquery.min.js"></script> <script type="text/javascript" src="js/Chart.min.js"></script> <script type="text/javascript" src="js/app.js"></script> </body> </html> app.js $.ajax({ type: 'POST', url: 'data.php', success: function (data) { lineChartData = JSON.parse(data); //parse the data into JSON var ctx = document.getElementById("mycanvas").getContext("2d"); var myLineChart = new Chart(ctx, { type: 'line', data: lineChartData }); } });
Loading data to jqGrid using AJAX and PHP
I have the following code in browser side. <!DOCTYPE html> <html> <head> <script src="js/jquery-1.10.2.min.js" type="text/javascript"></script> <script src="js/jquery-ui-1.10.3.custom.min.js" type="text/javascript"></script> <script src="js/grid.locale-en.js" type="text/javascript"></script> <script src="js/jquery.jqGrid.min.js" type="text/javascript"></script> <link href="css/jquery-ui-1.10.3.custom.min.css" rel="stylesheet" type="text/css" media="screen"/> <link href="css/ui.jqgrid.css" rel="stylesheet" type="text/css" media="screen"/> <link href="css/jqGrid.css" rel="stylesheet" type="text/css" media="screen"/> <script type="text/javascript"> $(document).ready(function () { $("#tblevents").jqGrid({ url: "getGridData.php", datatype: "json", mtype: "POST", postData: { search: function() { return 'manage'; } }, colModel: [ {name:'id',index:'id',label:'ID', width:10}, {name:'eventdate',index:'eventdate',label:'Event date', width:100, align:'center', sorttype:'date'}, {name:'reportdate',index:'reportdate',label:'Report date', width:180, align:'left'}, {name:'eventdescription',index:'eventdescription',label:'Description', width:430} ], rowNum: 10, rowList: [10,20], pager: '#pager', height: '100%', width: 'autowidth', viewrecords: true, gridview: true, caption: "ATM-ANS Occurrences" }); }); </script> </head> <body> <div class="mycenter"> <table id='tblevents'></table> <div id='pager'></div> </div> </body> </html> The server side code. <?php $sqconn = "mysql:host=localhost;dbname=eoccurrence"; $dbh = new PDO($sqconn, 'user', ''); $page = $_POST['page']; $limit = $_POST['rows']; $sidx = $_POST['sidx']; $sord = $_POST['sord']; if(!$sidx) {$sidx =1;} try { $SQLQues = "SELECT COUNT(*) AS count FROM event"; $cmd = $dbh->query($SQLQues, PDO::FETCH_ASSOC); $res = $cmd->fetchAll(); $count = $res[0]['count']; if( $count > 0 && $limit > 0) {$total_pages = ceil($count/$limit);} else {$total_pages = 0;} if ($page > $total_pages) {$page=$total_pages;} $start = $limit*$page - $limit; if($start <0) {$start = 0;} $SQLQues = "SELECT ID, date_format(eventdate, '%d-%m-%Y %H:%i') AS eventdate, " . "date_format(reportDate, '%d-%m-%Y') AS reportdate, SUBSTRING(eventdescription,1,70) AS eventdescription " . "FROM event" . " ORDER BY event.eventdate DESC LIMIT $start , $limit"; $cmd = $dbh->query($SQLQues, PDO::FETCH_BOTH); $i=0; while ($row = $cmd->fetch()) { $responce->rows[$i]['id']=$row['ID']; $responce->rows[$i]['cell']=array($row['eventdate'],$row['reportdate'],$row['eventdescription']); $i++; } echo json_encode($response); return; } catch (PDOException $exc) { echo $exc->getTraceAsString(); } The $response that is encoded from php to browser is shown in the following image, capture with XDebug. The resulting grid is as shown below, with no row data at all. What I'm doing wrong?
<script type="text/javascript"> $(document).ready(function () { $("#tblevents").jqGrid({ url: "getGridData.php", datatype: "json", mtype: "POST", colNames: ["Id","eventdate", "reportdat", "event description"], colModel: [ {name:'id'}, {name:'eventdate'}, {name:'reportdate'}, {name:'eventdescription'} ], pager: "#pager", rowNum: 10, rowList: [10,20], sortorder: "asc", height: 'auto', viewrecords: true, gridview: true, caption: "ATM-ANS Occurrences" }); });
Getting data in a text file after updating it on highcharts but initially retrieving from csv file
I am actually trying to do exactly what has been done in this example "http://jsfiddle.net/BrLp7/" but unfortunately not able to perform this task when retrieving data from csv file. Below is my code which doesn't output anything and when we click on a point in a given example the resulting graph has to be stored in some text file in this form 5,10,13 if last point was clicked. <html> <head> <title>A BASIC HTML FORM</title> </head> <body> <FORM NAME ="form1" METHOD ="POST" ACTION = "BasicForm.php"> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Highcharts Example</title> <!-- 1. Add these JavaScript inclusions in the head of your page --> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script type="text/javascript" src="../js/highcharts.js"></script> <!--[if IE]> <script type="text/javascript" src="../js/excanvas.compiled.js"></script> <![endif]--> <!-- 2. Add the JavaScript to initialize the chart on document ready --> <script type="text/javascript"> $(document).ready(function() { var options = { chart: { renderTo: 'container', defaultSeriesType: 'line' }, title: { text: 'Input' }, xAxis: { categories: [] }, yAxis: { title: { text: 'Units' } }, plotOptions: { series: { cursor: 'pointer', point: { events: { click: function() { $.get('testFile.csv', function(data) { // Split the lines var lines = data.split('\n'); $.each(lines, function(lineNo, line) { var x=this.series.processedXData.indexOf(this.x); var items = line.split(','); seriesData =[]; $.each(items, function(itemNo, item) { if (itemNo < x) { seriesData.push(parseFloat(item)); } else if (itemNo == x){ seriesData.push(0); } }); } this.series.setData(seriesData); } } } }, series: [] }; $.get('testFile.csv', function(data) { // Split the lines var lines = data.split('\n'); $.each(lines, function(lineNo, line) { var items = line.split(','); var series = { data: [] }; $.each(items, function(itemNo, item) { series.data.push(parseFloat(item)); }); options.series.push(series); }); var chart = new Highcharts.Chart(options); }); }); </script> </head> <body> <script src="http://code.highcharts.com/highcharts.js"></script> <script src="http://code.highcharts.com/modules/data.js"></script> <script src="http://code.highcharts.com/modules/exporting.js"></script> <!-- 3. Add the container --> <div id="container" style="width: 1400px; height: 400px; margin: 0 auto"></div> </body> </html> </FORM> </body> </html>
Highchart and php
Hi guys i m trying to pass value from my php to highchart dataset but its not working help needed. <?php $count2=$decode[nextPage][totalResults]; echo("<input type=hidden name=aaqib value=".$count.">"); ?> <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Highcharts Example</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <script type="text/javascript"> $(function () { var chart; var j= $("input[name=aaqib]").val(); var k=100; $(document).ready(function() { chart = new Highcharts.Chart({ chart: { renderTo: 'container' }, title: { text: 'Logarithmic axis demo' }, xAxis: { tickInterval: 1 }, yAxis: { type: 'logarithmic', minorTickInterval: 0.1 }, tooltip: { headerFormat: '<b>{series.name}</b><br />', pointFormat: 'x = {point.x}, y = {point.y}' }, series: [{ data: [j,k, pointStart: 1 }] }); }); }); </script> </head> <body> <script src="../../js/highcharts.js"></script> <script src="../../js/modules/exporting.js"></script> <div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div> </body> </html> Hi guys i m trying to pass value from my php to highchart dataset but its not working help needed. i need to use value of J and K in data so that they are shown in highcharts
Store your php vars into a js vars and then pass to highcharts. Fix the following too. echo('<input type="hidden" name="aaqib" value="{$count}"/>'); Update according to this comment. series: [{ data: [[j,k]] }] Tthis demo should help you.
why are you echoing the input above your doctype declaration? I think that belongs inside your body. And you should also '-signs around the attribute values in you echo. something like this: <?php $count2=$decode[nextPage][totalResults]; echo("<input type='hidden' name='aaqib' value='$count'>"); ?> Some browsers might threat this correctly, but it's actualy invalid html