Data from MongoDB results with empty Highcharts graph - php
I just started with MongoDB. I need to display data from MongoDB in graphs and plots. To do that I am using Highcharts with PHP.
Problem is that when I run simple query, I get results (I loop results inside foreach loop) but when I echo same results in Highcharts series data I got nothing. Chart is empty without any line.
I want to display all test data of particular station (in this example station is Alpha1) grouped in days.
Does someone know where is the problem?
Here is example of MongoDB record:
"id": 3,
"date": "2015-07-19",
"name": "StressTest",
"first_test": 4279.558451,
"second_test": 4296.838515,
"third_test": 825.446594,
"min": 2.827739,
"max": 6071.036922,
"station": "Alpha1"
}
and here code that I am using:
<?php
$dbname = 'db';
$m = new MongoClient("mongodb://root:toor#localhost:55732/db");
$db = $m->$dbname;
$collection = $db->db;
$results = $collection->find()->limit(10);
foreach ($results as $result){
echo $result["name"]."<br>";//I got result here
}
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/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>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
<script>
$(function () {
$('#container').highcharts({
series: [{data: <?php echo json_encode($results) ?>, name: 'graph data'}]
});
});
</script>
</body>
</html>
Per the Highcharts docs on Series, you need to send data in a valid format (a list of numbers).
Try to inspect the source this generates, it's probably something like
<script>
$(function () {
$('#container').highcharts({
series: [{data:
{
"_id" : ObjectId("55d24118cb924da44d039ea6"),
"date": "2015-07-19",
"name": "StressTest",
"first_test": 4279.558451,
"second_test": 4296.838515,
"third_test": 825.446594,
"min": 2.827739,
"max": 6071.036922,
"station": "Alpha1"},
{"_id: // .... and so on
, name: 'graph data'}]
});
});
</script>
You need to echo a list of numbers you wish to plot, not just output documents directly from Mongo.
If you meant to graph first_test, second_test, and third_test as their own lines, you need to group each into their own series:
$results = $collection->find()->limit(10);
$series = array('first_test'=>[], 'second_test'=>[], 'third_test'=>[]);
$xAxis = array();
foreach ($results as $result){
foreach($series as $key => $values){
$series[$key][] = $result[$key];
}
$xAxis[] = $result['date'];
}
Then output each series separately:
<script>
$(function () {
$('#container').highcharts({
xAxis: {
categories: [<?php echo json_encode($xAxis); ?> ]
},
series: [
<?php foreach($series as $key => $dataPoints){ ?>
{
data: <?php echo json_encode($dataPoints) ?>,
name: '<?php echo $key ?>'
}
<?php }// End foreach ?>
]
});
});
</script>
Check out their example Fiddle with a similar chart type here.
Related
highchart load the chart but not the JSON data
I'm trying to use highcharts to draw data from php json. the php works ok but i dont know how to make the json an input. Speciffically 'm trying to put the data on single Gauge Chart like the one on the example, but i can't configure the script to read the json. The URL si this: php/KPItonsStock.php <?php function getArraySQL(){ $startd = "29964"; $endd = "29968"; $dsn = "prueba"; $connect = odbc_connect( $dsn, '', '' ); $query = " Select SUM(TON_DESCARGADO) AS data from (Select unit,[load],enum_LOAD.[name],SUM(dumptons) as TON_DESCARGADO from hist_dumps inner join hist_loclist on hist_dumps.shiftindex = hist_loclist.shiftindex and hist_dumps.loc = hist_loclist.locid inner join enum_LOAD on hist_dumps.[load] = enum_LOAD.[num] where hist_dumps.shiftindex between '$startd' and '$endd' GROUP BY loc,UNIT,unit#,[load],enum_LOAD.[name])TEMP1 where unit = 'Stockpile' GROUP BY unit order BY UNIT"; if(!$rs = odbc_exec($connect, $query)) die(); $rawdata = array(); $i=0; while($row = odbc_fetch_array($rs)) { $rawdata[$i] = $row; $i++; } odbc_close( $connect ); return $rawdata; }; $data = getArraySQL(); echo json_encode(($data), JSON_NUMERIC_CHECK); and the result is this: [{"data":29655.88482666}] so i need to put information from that URL to the gauge chart. Im trying with getjson, but I'm missing something, because the chart loads but not the data. This is the otriginal highchart example http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/gauge-solid/ This is the example with my data <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.8.2/jquery.min.js"></script> <script src="http://code.highcharts.com/highcharts.js"></script> <script src="http://code.highcharts.com/highcharts-more.js"></script> <script src="http://code.highcharts.com/modules/solid-gauge.js"></script> <style type="text/css"> ${demo.css} </style> <script type="text/javascript"> function visitorData (data) { $('#container').highcharts({ chart: { type: 'solidgauge' }, title: { text: 'Average Visitors' }, pane: { center: ['50%', '85%'], size: '140%', startAngle: -90, endAngle: 90, background: { backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || '#EEE', innerRadius: '60%', outerRadius: '100%', shape: 'arc' } }, yAxis: { min: 0, max: 40000, title: { text: 'Speed'}, stops: [ [0.1, '#55BF3B'], // green [0.5, '#DDDF0D'], // yellow [0.9, '#DF5353'] // red ], lineWidth: 0, minorTickInterval: null, tickPixelInterval: 400, tickWidth: 0, title: { y: -70 }, labels: { y: 16 } }, series: data, }); } $(document).ready(function() { $.ajax({ url: 'report2/KPItonsStock.php', type: 'GET', async: true, dataType: "json", success: function (data) { visitorData(data); } }); }); </script> </head> <body> <div style="width: 600px; height: 400px; margin: 0 auto"> <div id="container" style="width: 300px; height: 200px; float: left"></div> </div> </body> </html> I get the graphic but it doesnt load any data
Data needs to be an array. Make your backend return [{ "data": [29655.88482666] }] http://jsfiddle.net/nicholasduffy/openzant/3/
ParamQuery Data Display
I am trying to implement ParamQuery an excel like plugin in php.I am trying to fetch the data from a php which generates json output.It is fetching properly but i want to display the datas within the div:grid_array in the specified format.Am not able to do that The fields are all coming blank. My json output code:data.php <?php $conn = mysql_connect('localhost','root','pass'); if(!$conn){ die('Mysql connection error '.mysql_error()); } $db = mysql_select_db('pop',$conn); if(!$db){ die('Database selection failed '.mysql_error()); } $sql = 'SELECT *FROM items'; $result = mysql_query($sql,$conn); $data = array(); while($row = mysql_fetch_array($result)){ $row_data = array( 'id' => $row['Item_id'], 'Product' => $row['Product'], 'Brand' => $row['Brand'], 'Model' => $row['Model'] ); array_push($data, $row_data); } echo json_encode($data); ?> my html file which should display the data: <html> <head> <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/themes/base/jquery-ui.css" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script> <!--PQ Grid files--> <link rel="stylesheet" href="pqgrid.min.css" /> <script src="pqgrid.min.js"></script> <!--PQ Grid Office theme--> <link rel="stylesheet" href="themes/office/pqgrid.css" /> <script> $(document).ready(function(){ var url = 'data.php'; $.getJSON(url, function(data) { $.each(data, function(index, data) { var obj = { width: 700, height: 400, title: "ParamQuery Grid Example",resizable:true,draggable:true }; obj.colModel = [{ title: "Id", width: 100, dataType: "integer" }, { title: "Product", width: 200, dataType: "string" }, { title: "Brand", width: 150, dataType: "string" }, { title: "Model", width: 150, dataType: "string"}]; obj.dataModel = { data:data}; $("#grid_array").pqGrid(obj); }); }); }); </script> </head> <body> <div id="grid_array" style="margin:100px;"> </div> </body> </html>
Maybe It's too late to answer already, anyway I see that you didn't set up colModel properly... I mean, you forgot to link the columns to the "fields". i.e.: { title: "Product", width: 200, dataType: "string", dataIndx: "Product" } where dataIndx is the JSON field; "title" is only the caption, but not directly the data binding... and as result what you can see is the row but blank I have based on paramgrid demo here You can see de dataIndx fields inside colModel structure...
Highcharts -- Getting categories from mysql
I am trying to get data from my mysql into Highcharts bar graph. I have the data from mysql that includes a port number and average bytes per port. Here is what I have for my php query and html page. The data (average bytes) shows up on the graph just fine. I can't get the categories (port) data to display. <?php $con = mysql_connect("localhost","root","kdkdkdk") or die(mysql_error()); mysql_select_db("silk", $con); $result = mysql_query("SELECT dstPortNum,avgByte FROM statistic_avgbytesport ORDER BY avgByte DESC LIMIT 10;"); $rows = array(); while($r = mysql_fetch_array($result)) { $row[0] = $r[0]; $row[1] = $r[1]; array_push($rows,$row); } print json_encode($rows, JSON_NUMERIC_CHECK); #print json_encode($rows[0][0], JSON_NUMERIC_CHECK); mysql_close($con); ?> And my html page to display the graph. <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Highcharts Pie Chart</title> <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: 'avgbytes' }, title: { text: 'Average Bytes Per Port' }, pane: { size:'80%' }, xAxis: { title: { text: 'PORTS' }, categories: [] }, yAxis: { min: 0, title: { text: 'Bytes' } }, series: [{ type: 'bar', name: 'Average Bytes', data: [] }] } $.getJSON("averageBytesPerPort.php", function(json) { options.series[0].data = json; chart = new Highcharts.Chart(options); }); }); </script> <script src="http://code.highcharts.com/highcharts.js"></script> <script src="http://code.highcharts.com/highcharts-more.js"></script> </head> <body> <div id="avgbytes" style="width: 300px; height: 300px; margin: 0 auto"></div> </body> </html>
You can use something like this: $.getJSON("averageBytesPerPort.php", function(json) { var options = { chart: { renderTo: 'avgbytes' }, title: { text: 'Average Bytes Per Port' }, pane: { size:'80%' }, xAxis: { title: { text: 'PORTS' }, categories: data.categories }, yAxis: { min: 0, title: { text: 'Bytes' } }, series: [{ type: 'bar', name: 'Average Bytes', data: data }] } chart = new Highcharts.Chart(options); });
how the hell on earth your data is shown , you have not put the $conn as the second parameter of the mysql_query(); it should be $result = mysql_query("SELECT dstPortNum,avgByte FROM statistic_avgbytesport ORDER BY avgByte DESC LIMIT 10;",$conn);
Data won't echo on Highcharts
I can't get my data to plot on the highchart but it shows up on the source, what am I doing wrong? I don't know if I am using the wrong syntax to echo my string from the hcdata.php. I have been having this problem with getting the output to show up on the actual chart from what I can see the data is correctly formatted it comes out like this: [Date.UTC(2013,05,31,10,39,36), 20179], [Date.UTC(2013,05,31,10,30,00), 20031], [Date.UTC(2013,05,31,10,09,36), 19684], [Date.UTC(2013,05,31,09,54,36), 19384], [Date.UTC(2013,05,31,09,39,36), 19039], [Date.UTC(2013,05,31,09,24,36), 18763], [Date.UTC(2013,05,31,09,09,36), 18435], [Date.UTC(2013,05,31,08,54,36), 18097], [Date.UTC(2013,05,31,08,39,36), 17788], [Date.UTC(2013,05,31,08,30,00), 17552], [Date.UTC(2013,05,31,08,09,36), 17169], [Date.UTC(2013,05,31,08,00,00), 16940], [Date.UTC(2013,05,31,07,45,00), 16608], [Date.UTC(2013,05,31,07,30,00), 16284], [Date.UTC(2013,05,31,07,15,00), 15922], [Date.UTC(2013,05,31,06,54,36), 15216], [Date.UTC(2013,05,31,06,39,36), 14724], [Date.UTC(2013,05,31,06,30,00), 14352], [Date.UTC(2013,05,31,06,09,36), 13713], [Date.UTC(2013,05,31,05,54,36), 13491], [Date.UTC(2013,05,31,05,39,36), 13660], [Date.UTC(2013,05,31,05,24,36), 13680], [Date.UTC(2013,05,31,05,09,36), 13548], [Date.UTC(2013,05,31,04,54,36), 13327], [Date.UTC(2013,05,31,04,45,00), 13263], [Date.UTC(2013,05,31,04,30,00), 13178], [Date.UTC(2013,05,31,04,09,36), 13105], [Date.UTC(2013,05,31,03,54,36), 13048], [Date.UTC(2013,05,31,03,39,36), 13054], [Date.UTC(2013,05,31,03,24,36), 13079], [Date.UTC(2013,05,31,03,15,00), 13138], [Date.UTC(2013,05,31,03,00,00), 13200], [Date.UTC(2013,05,31,02,39,36), 13330], [Date.UTC(2013,05,31,02,24,36), 13409], [Date.UTC(2013,05,31,02,15,00), 13512], [Date.UTC(2013,05,31,01,54,36), 13675], [Date.UTC(2013,05,31,01,39,36), 13825], [Date.UTC(2013,05,31,01,24,36), 13986], [Date.UTC(2013,05,31,01,15,00), 14143], [Date.UTC(2013,05,31,00,54,36), 13851], [Date.UTC(2013,05,31,00,39,36), 14066], [Date.UTC(2013,05,31,00,24,36), 14303], [Date.UTC(2013,05,31,00,09,36), 14591] <?php include "data.php"; ?> <?php include "hcdata.php"; ?> <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title></title> <script type="text/javascript" src="''/SQLPHP/js/jquery.min.js"></script> <script src="''/SQLPHP/js/highcharts.js"></script> <script src="''/SQLPHP/js/modules/exporting.js"></script> <script type="text/javascript"> $(function () { var data = [ [<?php echo $finalString; ?>] ]; data.sort(function(a,b) { return a[0] - b[0]; }); $('#container').highcharts({ chart: { type: 'spline' }, title: { text: 'Forecast vs Actual Load [VM]' }, subtitle: { text: 'This chart displays the time and actual forecast load for this region' }, xAxis: { type: 'datetime', dateTimeLabelFormats: { // don't display the dummy year month: '%e. %b', year: '%b' } }, yAxis: { title: { text: 'Actual Load (WM)' }, min: 0 }, tooltip: { formatter: function() { return '<b>'+ this.series.name +'</b><br/>'+ Highcharts.dateFormat('%e. %b', this.x) +': '+ this.y +' m'; } }, series: [{ name: 'Forecast vs Actual Load', // Define the data points. All series have a dummy year // of 1970/71 in order to be compared on the same x axis. Note // that in JavaScript, months start at 0 for January, 1 for February etc. data: data }] }); }); </script> </head> <body> <div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div> </body> </html>
Your PHP data insert looks like it is wrapping the data in 2 [] blocks: var data = [ [<?php echo $finalString; ?>] ]; You need to wrap your entire data set in one []. Such that it looks like: var data = [ <?php echo $finalString; ?> ]; You should end up with this: [ [Date.UTC(2013,05,31,10,39,36), 20179], [Date.UTC(2013,05,31,10,30,00), 20031], [Date.UTC(2013,05,31,10,09,36), 19684], [Date.UTC(2013,05,31,09,54,36), 19384], [Date.UTC(2013,05,31,09,39,36), 19039], [Date.UTC(2013,05,31,09,24,36), 18763], [Date.UTC(2013,05,31,09,09,36), 18435], [Date.UTC(2013,05,31,08,54,36), 18097], [Date.UTC(2013,05,31,08,39,36), 17788], [Date.UTC(2013,05,31,08,30,00), 17552], [Date.UTC(2013,05,31,08,09,36), 17169], [Date.UTC(2013,05,31,08,00,00), 16940], [Date.UTC(2013,05,31,07,45,00), 16608], [Date.UTC(2013,05,31,07,30,00), 16284], [Date.UTC(2013,05,31,07,15,00), 15922], [Date.UTC(2013,05,31,06,54,36), 15216], [Date.UTC(2013,05,31,06,39,36), 14724], [Date.UTC(2013,05,31,06,30,00), 14352], [Date.UTC(2013,05,31,06,09,36), 13713], [Date.UTC(2013,05,31,05,54,36), 13491], [Date.UTC(2013,05,31,05,39,36), 13660], [Date.UTC(2013,05,31,05,24,36), 13680], [Date.UTC(2013,05,31,05,09,36), 13548], [Date.UTC(2013,05,31,04,54,36), 13327], [Date.UTC(2013,05,31,04,45,00), 13263], [Date.UTC(2013,05,31,04,30,00), 13178], [Date.UTC(2013,05,31,04,09,36), 13105], [Date.UTC(2013,05,31,03,54,36), 13048], [Date.UTC(2013,05,31,03,39,36), 13054], [Date.UTC(2013,05,31,03,24,36), 13079], [Date.UTC(2013,05,31,03,15,00), 13138], [Date.UTC(2013,05,31,03,00,00), 13200], [Date.UTC(2013,05,31,02,39,36), 13330], [Date.UTC(2013,05,31,02,24,36), 13409], [Date.UTC(2013,05,31,02,15,00), 13512], [Date.UTC(2013,05,31,01,54,36), 13675], [Date.UTC(2013,05,31,01,39,36), 13825], [Date.UTC(2013,05,31,01,24,36), 13986], [Date.UTC(2013,05,31,01,15,00), 14143], [Date.UTC(2013,05,31,00,54,36), 13851], [Date.UTC(2013,05,31,00,39,36), 14066], [Date.UTC(2013,05,31,00,24,36), 14303], [Date.UTC(2013,05,31,00,09,36), 14591] ]
json encoding php for fetching the data from the database ang showing it to te graph
I have written the following code for fetching the data from the database: $result = mysql_query("select projid,projname,enddate,status from projects where kunnr='".$_SESSION["kunnr"]."'"); $model['dash']=array(); while($row = mysql_fetch_array($result)){ array_push($model['dash'], array( "id"=>$row["projid"], "projname"=>$row["projname"], "enddate"=>$row["enddate"], "status"=>$row["status"], )); } and the following code for showing these data on the graph(chart).. $(document).ready(function() { chart1 = new Highcharts.Chart({ chart: { renderTo: 'container1', type: 'column' }, title: { text: 'Service Calls-Days Over' }, xAxis: { categories:[ <?php foreach($model["dashchart"] as &$obj){?> '<?php echo $obj["name"];?>', <?php }?>] }, yAxis: { }, series: [{ name: 'Service Calls-Days Over', color:'#e48801', data: [<?php foreach($model["dashchart"] as &$obj){?> <?php echo $obj["days"];?>, <?php }?>] } ] }); overhere i have used php coding but i want to do it by json encoding.. please suggest me...
use json_encode.. For example: categories: <?php echo json_encode($model["dashchart"]); ?>
Please try with jQuery.getJSON http://api.jquery.com/jQuery.getJSON/ function.