How to show MySQL data in graph? - javascript

I want to retrieve data from mysql in the form of graph with the following code. But, nothing is shown. Can anybody help me?
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "graphdata.php",
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
var options = {'title':'Ticket Sales','width':500,'height':400};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data,options);
}
</script>
<?php
echo("<div id='chart_div'></div>");
?>
Here is my getdata.php:
$sql = "SELECT count(`booth_number`),`sold_by` FROM `registration1` where week(`Date`) = week(curdate()) GROUP BY `sold_by`";
$result = mysql_query($sql, $conn) or die(mysql_error());
//start the json data in the format Google Chart js/API expects to recieve it
$data = array(
'cols' => array(
array('label' => 'Month', 'type' => 'string'),
array('label' => 'Ticket Sales', 'type' => 'string')
),
'rows' => array()
);
while($row = mysql_fetch_row($result)) {
$data['rows'][] = array('c' => array(array('v' => $row[0]), array('v' => $row[1])));
}
echo json_encode($data);

As mentioned, I think you need to move your code inside the success callback:
function drawChart() {
$.ajax({
url: "graphdata.php",
type: "GET",
dataType:"json",
success: function(jsonData, textStatus, jqXHR) {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
var options = {'title':'Ticket Sales','width':500,'height':400};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data,options);
}
});
}
[edit] A working example (with some mocked data) can be found on jsBin.
[edit2] Update the example on jsBin with the output provided in the duplicate question:
{
"cols": [
{
"label":"Month",
"type":"string"
},{
"label":"Weekly Sales",
"type":"string"
}
],
"rows": [
{
"c":[
{"v":"3"},
{"v":"jaspreet singh "}
]
},{
"c":[
{"v":"3"},
{"v":"joseph swanson"}
]
}
]
}
The JSON returned by the server is wrong, the object should look like this:
"cols": [
{
"label":"Month",
"type":"string"
},{
"label":"Weekly Sales",
"type":"number"
}
],
"rows": [
{
"c":[
{"v":"jaspreet singh "},
{"v":"3"}
]
},{
"c":[
{"v":"joseph swanson"},
{"v":"3"}
]
}
]
};
The changes needed should now be obvious. Hope this helps.
[edit3] getdata.php should contain the following snippet imho:
$data = array(
'cols' => array(
array('label' => 'Month', 'type' => 'string'),
array('label' => 'Ticket Sales', 'type' => 'number')
),
'rows' => array()
);
while($row = mysql_fetch_row($result)) {
$data['rows'][] = array(
'c' => array(
array('v' => $row[1]),
array('v' => $row[0])
)
);
}

Related

DataTable not accepting json from database

I want to set up a datatable on my website and I found a table I want to use here and I have been trying to convert it over to what I need. I have not had much success in this endeavor. My current situation is the table is not populating with rows from a database table and I am getting a json response error. I can open the inspector look at the php file that queries the database returns json data and I can see that I am returning data in the format
{"data":[
{"ssn":"100192686","dob":"1977-02-01","fn":"Latoyia","mi":"H","ln":"Herdon"},
{"ssn":"100263201","dob":"1962-06-15","fn":"Adena","mi":"M","ln":"Couch"}
]}
which according to a json validator is valid json but when I reload my page I get an error
"table id=example - Invalid JSON response".
So if the json data is in the correct format but is not being returned correctly what do I do? here is a gihub for the project. I have included the mysql database file I am working with as well as a text file that has XHR results in it. I feel like this line $('#example').DataTable( { javascript is where my issue is
<?php
include_once 'header.php';
?>
<script src = 'https://code.jquery.com/jquery-1.12.4.js'></script>
<script src = 'https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js'></script>
<script src = 'https://cdn.datatables.net/buttons/1.5.1/js/dataTables.buttons.min.js'></script>
<script src = 'https://cdn.datatables.net/select/1.2.5/js/dataTables.select.min.js'></script>
<script src = 'JS/dataTables.editor.min.js'></script>
<link rel = "stylesheet" href = "https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css">
<link rel = "stylesheet" href = "https://cdn.datatables.net/buttons/1.5.1/css/buttons.dataTables.min.css">
<link rel = "stylesheet" href = "https://cdn.datatables.net/select/1.2.5/css/select.dataTables.min.css">
<link rel = "stylesheet" href = "https://editor.datatables.net/extensions/Editor/css/editor.dataTables.min.css">
<section class="main-container">
<div class="main-wrapper">
<h2>Home</h2>
<?php
if (isset($_SESSION['u_id'])) {
$sql = "SELECT * FROM employee;";
$result = mysqli_query($conn,$sql);
$resultCheck = mysqli_num_rows($result);
if($resultCheck > 0){
echo
"<table id='example' class='display' cellspacing='0' width='100%'>
<thead>
<tr>
<th></th>
<th>ssn</th>
<th>dob</th>
<th>first</th>
<th>MI</th>
<th>last</th>
</tr>
</thead>";
}
}
?>
</div>
</section>
<script>
console.log("In the script open");
var editor; // use a global for the submit and return data rendering in the examples
$(document).ready(function() {
editor = new $.fn.dataTable.Editor( {
ajax: "infograb.php",
table: "#example",
fields: [ {
label: "Social#:",
name: "ssn"},
{
label: "DOB:",
name: "dob"},
{label: "First Name:",
name: "fn"},
{
label: "Middle Initial:",
name: "mi"},
{
label: "Last Name:",
name: "ln"
}
]
} );
$('#example').on( 'click', 'tbody td', function (e) {
var index = $(this).index();
if ( index === 1 ) {
editor.bubble( this, ['fn', 'mi', 'ln'], {
title: 'Edit name:'
} );
}
else if ( index === 2 ) {
editor.bubble( this, {
buttons: false
} );
}
else if ( index === 3 ) {
editor.bubble( this );
}
} );
var testData = [{
"ssn": "98727748",
"dob": "2016-02-05",
"fn": "jake",
"mi": "a",
"ln": "butler"
}];
$('#example').DataTable( {
dom: "Bfrtip",
ajax:{
url: 'infograb.php',
type: 'POST',
data: {
json: JSON.stringify({ "data": testData })
},
dataSrc: 'data'
},
columns: [
{//sets the checkbox
data: null,
defaultContent: '',
className: 'select-checkbox',
orderable: false
},
{ data: "dob" },
{ data: "ssn" },
{ data: "fn" },
{ data: "mi" },
{ data: "ln" },
],
order: [ 1, 'asc' ],
select: {
style: 'os',
selector: 'td:first-child'
},
buttons: [
{ extend: "create", editor: editor },
{ extend: "edit", editor: editor },
{ extend: "remove", editor: editor }
]
} );
} );
console.log("End script");
</script>
<?php
include_once 'footer.php';
?>
and here is the php file that queries the database and returns(allegedly) the json data
<?php
include_once 'dbconn.php';
$rows = array();
$sql = "SELECT * FROM employee";
$result = $conn->query($sql) or die("cannot write");
while($row = $result->fetch_assoc()){
$rows[] = $row;
}
echo "<pre>";
print json_encode(array('data'=>$rows));
echo "</pre>";
?>
I have been at this for about 24 hours now, and I feel like I have a bonehead mistake here I just can't figure it out. Any help would talk me down off the cliff at this point.
Datatables can be a pain and it's worthwhile to make sure you read the documents provided by them as much as you can.
I can see 2 issues running over your code without running tests. First one is infograb.php won't save any data sent to it because all it does is return data when it's loaded. Secondly you are using the initiation code of the datatable to try and send data (presumably for the inline editing as you don't seem to require any variables to be sent for the data requested). My first step would be taking it back a step:
ajax:{
url: 'infograb.php',
type: 'POST',
data: {
json: JSON.stringify({ "data": testData })
},
dataSrc: 'data'
},
Should go back to
ajax:{
url: 'infograb.php',
},
Remove the pre tags from infograb.php as well as they are unnecessary.
That should load the data into the table for you. You can then start working on the editing side.
Worthwhile Reading and Documentation:
Ajax sourced data
PHP libraries
DataTables Editor 1.7.3 - PHP 5.3+ libraries

How to read in data array return from ajax for google chart?

var e = $.ajax({
type: "POST",
url: "<?php echo $template->get_template_dir('ajax',DIR_WS_TEMPLATES, $current_page_base,'ajax'); ?>/survey_save.php",
data: str
}).done(function(data) {
alert("Survey has been saved."+data);
$('#form').hide();
$('#results').show();
// data array for google chart
var e = [["Element", "Density", { role: "style" } ],["Copper", 8.94, "#b87333"],["Silver", 10.49, "silver"],["Gold", 19.30, "gold"],["Platinum", 21.45, "color: #e5e4e2"]];
return e;
});
google.charts.load("current", {packages:['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable(e);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{ calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation" },
2]);
var options = {
title: "Density of Precious Metals, in g/cm^3",
width: 600,
height: 400,
bar: {groupWidth: "95%"},
legend: { position: "none" },
};
var chart = new google.visualization.ColumnChart(document.getElementById("columnchart_values"));
chart.draw(view, options);
}
}
So the code above will return the data array as JSON. I need to either return it as an array or convert the JSON to an array format. How could I do that? When trying to call the
Explanation:
Pass AJAX request and get response data in JSON using mysql query. Feed response data to chart function.
In short, you need to get array values -> convert into JSON and give those values to google chart irrespective whether you need mysql or not. Modify code according to your requirement.
Client side main php
<script>
drawLineChart('<?php echo strtolower($chartType); ?>');
</script>
Client side function php
function drawLineChart(chartType, chartTitle) {
google.charts.setOnLoadCallback(lineChartData);
function lineChartData() {
var lineChartJsonData = $.ajax({
type: 'GET',
url: "<?php echo $server_script_path; ?>",
data: { id1: chartType, id2: "Chart" },
dataType:"json",
async: false,
beforeSend: function() {
},
success: function(data) {
},
}).responseText;
var options;
options = {
title: chartTitle,
width: '390',
height: '300',
vAxis: {title: '<title>'},
};
var data = new google.visualization.arrayToDataTable(($.parseJSON(lineChartJsonData)));
var chart = new google.visualization.LineChart(document.getElementById(chartType));
chart.draw(data, options);
}
}
Server side php file
if ($_GET['id1'] != "" && $_GET['id2'] == "Chart") {
// Chart type
$chartType = explode('-', $_GET['id1'])[1];
$sql = "<mysql query>";
$result = mysqli_query($conn, $sql);
$table = array();
$rows = array();
$rows[] = array('<column1>', '<column2>');
while($row = mysqli_fetch_array($result)) {
$rows[] = array('<rows>', '<rows>');
}
$table = $rows;
echo json_encode($table);
}
Live chart (my array data)

How to pass nested foreach Values to CanvasJS chart?

I do some calculations with below Code and after that i want to pass the values to the Chart but i can not send them i have try this:
$getStoreIDs = mysqli_query($dbConnection, "SELECT DISTINCT Stores_storeID FROM maintable WHERE Survey_surveyId = '$surveyID' ");
while ($row = mysqli_fetch_array($getStoreIDs))
{
$storeIDarray[] = $row;
}
foreach($_POST['sections'] as $selected)
{
foreach ($storeIDarray as $key => $row)
{
$storeID = $row['Stores_storeID'];
$storeNames= mysqli_query($dbConnection , "SELECT storeName FROM stores WHERE storeID = '".$row['Stores_storeID']."'");
$sectinName = mysqli_query($dbConnection , "SELECT sectionName FROM sections WHERE sectionID = '$selected' ");
$totalSections = mysqli_query($dbConnection, "SELECT SUM(itemPrice) AS totalSection FROM maintable WHERE items_Family_Sections_sectionID='$selected' AND Stores_storeID = '$storeID' AND Survey_surveyId = '$surveyID' ");
}
}
i want to pass the values of ($storeNames, $ectionName and $totalSelections)
and here is my CanvasJs code `
var chart1 = new CanvasJS.Chart("chartContainer1",
{
title:{
text: "Store Comparision"
},
animationEnabled: true,
axisY: {
title: "Total Price"
},
legend: {
verticalAlign: "bottom",
horizontalAlign: "center"
},
theme: "theme2",
data: [
{
type: "column",
showInLegend: true,
legendMarkerColor: "grey",
dataPoints: [
]
}
]
});
chart1.render();`
First you need to put your javascript code before canvas chart,it renders.
How you are passing data to your view is important.Are you passing as json object or array?
If as json then need to parse in javscript before sending encoded in php.
In datapoints paraemeter you can pass like this
dataPoints: JSON.parse(<?php echo json_encode($json_managers) ?>)
Or can do via PHP before sending (A sample code snippet)
$managers = DB::table('orders')
->join('managers', 'orders.manager_id', '=', 'managers.id')
->groupBy('managers.manager_name')
->get(['managers.manager_name',DB::raw("sum(orders.sale) as sale")]);
foreach($managers as $key => $value){
$point = array("label" => $value->manager_name , "y" => $value->sale);
array_push($data_manager_points, $point);
}
$json_managers = json_encode($data_manager_points,JSON_NUMERIC_CHECK);
For more get here :
http://canvasjs.com/forums/topic/how-can-i-use-php-mysql-dynamic-data/

JSON Highcharts to draw multiple lines

I'm totally lost with Highcharts!. I have to draw a graph with multiple lines. I need a JSON output like this:
[{
"name": "2",
"data":
[1398333600000,1],[1398333600000,1],....
},
{
"name": "16",
"data":
[1398333600000,1],[1398333600000,1]...
},
{
....
....
}
]
...but, I get only a malformed JSON response from PHP file. ¿Some altruistic soul can enlighten the way? thank you very much in advance. Sorry, I am a super-newbie :(
My BD table Mysql:
i can´t upload a image with table BD on post, sorry! ...i need at least 10 reputation!
...link...
http://i57.tinypic.com/2efj43n.jpg
The javascript code:
chart = new Highcharts.Chart({
chart: {
renderTo: 'divStatsGrupo',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: titulo
},
tooltip: {
enabled: false,
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats : {
hour: '%H:%M',
labels: {
style: {
width: '200px','min-width': '100px'
},
useHTML : true
}
}
},
yAxis: {
categories: [ 'APAGADO', 'ACTIVO', 'ALARMA'],
title: {
text: 'ESTADO'
},
min: 0
},
series : [{
showInLegend: true,
name : data.name,
type : 'line',
data: data.data
}]
});
});
And the PHP code:
require_once('Connections/conexion.php');
$sesionUser = $_SESSION['MM_Username'];
$sesionIdGrupo = $_GET['idGrupo'];
$sesionFechaActual = $_GET['fechaActual'];
///ARREGLO FECHA RECIBIDA PARA ADAPTARLA A FORMATO DE LA BD YY-MM-DD
$sesionFechaActualArreglo = date_format(new DateTime($sesionFechaActual),"Y-m-d");
mysql_select_db($database_conexion, $conexion);
$query_RecordsetTabla = "SELECT * FROM registros WHERE idUsuario = (SELECT idUsuario FROM usuarios WHERE userName = '$sesionUser') AND idGrupo = '$sesionIdGrupo' AND fecha = '$sesionFechaActualArreglo'";
$RecordsetTabla = mysql_query($query_RecordsetTabla, $conexion) or die(mysql_error());
$totalRows_RecordsetTabla = mysql_num_rows($RecordsetTabla);
$arr = array();
while ($row_RecordsetTabla = mysql_fetch_assoc($RecordsetTabla))
{
$idDispositivo = $row_RecordsetTabla['idDispositivo'];
$fecha = $row_RecordsetTabla['fecha'];
$hora = $row_RecordsetTabla['hora'];
$estado = $row_RecordsetTabla['estado'];
$arregloFecha = date_format(new DateTime($fecha),"Y-m-d");
$arregloHora = date_format(new DateTime($hora),"H:i");
$arregloHora2 = strtotime($arregloHora) * 1000;
$arr[] = array($arregloHora2, floatval($estado));
$arrDisp[] = array(floatval($idDispositivo));
}
$arr2 = array('data' => $arr, 'name' => $arrDisp);
echo json_encode($arr2);
mysql_free_result($RecordsetTabla);
I recieve this from PHP file...
{"data":[[1398330000000,1],[1398332700000,1],[1398331800000,1],[1398332700000,1]],"name":[[2],[2],[16],[16]]}
I think I have problems with arrays, Gracias!
You're very close. I kept the code as similar to yours so you can see the minor differences.
$items = array();
while ($row_RecordsetTabla = mysql_fetch_assoc($RecordsetTabla))
{
$idDispositivo = $row_RecordsetTabla['idDispositivo'];
$fecha = $row_RecordsetTabla['fecha'];
$hora = $row_RecordsetTabla['hora'];
$estado = $row_RecordsetTabla['estado'];
$arregloFecha = date_format(new DateTime($fecha),"Y-m-d");
$arregloHora = date_format(new DateTime($hora),"H:i");
$arregloHora2 = strtotime($arregloHora) * 1000;
// changed $arr and $arrDisp to scalar
$arr = array($arregloHora2, floatval($estado));
$arrDisp = array(floatval($idDispositivo));
// name and data should be put as part of a single array
$items[] = array ( 'data' => $arr , 'name' => $arrDisp );
}
// $arr2 = array('data' => $arr, 'name' => $arrDisp);
echo json_encode($items);
mysql_free_result($RecordsetTabla);
Please note I wasn't able to test it out, but if it does not work, let me know and I'll look at it further.
In your json_encode, I advice to set JSON_NUMERIC_CHECK, then numbers will not be a strings.

Highcharts json php multiple series

I have a simple question but for some reason can't find the solution. As described here: highcharts documentation, I made the following script:
<script type="text/javascript">
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'column',
},
title: {
text: 'Dagelijks waterverbruik'
},
subtitle: {
text: 'Waterverbruik in liters'
},
xAxis: {
categories: [
'Zondag',
'Maanag',
'Dinsdag',
'Woensdag',
'Donderdag',
'Vrijdag',
'Zaterdag'
]
},
yAxis: {
min: 0,
title: {
text: 'Waterverbruik (Liter)'
}
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{}]
};
$.getJSON('testdata.php', function(data) {
options.series[0].data = data;
var chart = new Highcharts.Chart(options);
});
});
</script>
my testdata.php is as follows:
<?php
header('Content-Type: application/json');
$data[] = array('Zondag',11);
$data[] = array('Maandag',10);
$data[] = array('Dinsdag',9);
$data[] = array('Woensdag',8);
$data[] = array('Donderdag',12);
$data[] = array('Vrijdag',2);
$data[] = array('Zaterdag',18);
$serie1[] = array('name' => 'serie 1', 'data' => $data);
$serie1[] = array('name' => 'serie 2', 'data' => $data);
echo json_encode($serie1);
?>
For some reason the charts don't render. What am I doing wrong? One series is working this way, but multiple series don't.
As you can see I would expect two bars with the same value. The output of testdata.php is:
[{"name":"serie 1","data":[["Zondag",11],["Maandag",10],["Dinsdag",9],["Woensdag",8],["Donderdag",12],["Vrijdag",2],["Zaterdag",18]]},{"name":"serie 2","data":[["Zondag",11],["Maandag",10],["Dinsdag",9],["Woensdag",8],["Donderdag",12],["Vrijdag",2],["Zaterdag",18]]}]
You make the array like this and do not use categories in the $data array because you are using static categories in chart.following is a hint
$data = array(11,10,9,8,12,81);
$serie1[] = array('name' => 'serie 1', 'data' => $data);
$serie1[] = array('name' => 'serie 2', 'data' => $data);
echo json_encode($serie1);
In this part:
$.getJSON('testdata.php', function(data) {
options.series[0].data = data;
var chart = new Highcharts.Chart(options);
});
Change it to this
$.getJSON('testdata.php', function(data) {
options.series = data;
var chart = new Highcharts.Chart(options);
});
You current code can only accomodate one series since you specified an index to the series i.e. [0].
In the JSON you need to set JSON_NUMERIC_CHECK flag, because in your example it seems that you have no numebr values on data.

Categories