Fusion Chart Multiple Charts With PHP & MySQl - javascript

I am generating a chart from fetching data in my MYSQL database. The JavaScript library I am using is Fusion Charts Suite XT. I have tried the following code which only renders one chart from one single query on a page. I am having trouble rendering another chart on the same HTML page.
<html>
<head>
<script type="text/javascript" src="../fusioncharts/js/fusioncharts.js"></script>
<script type="text/javascript" src="../fusioncharts/js/themes/fusioncharts.theme.zune.js"></script>
<?php
include('assets/global/plugins/fusioncharts/fusioncharts.php');
include('resource/dashboard/rank_chart.php'); ?>
</head>
<body>
<div id="chart-1"></div>
</body>
</html>
This is the code inside the fusioncarts.php include in the page.
<?php
class FusionCharts {
private $constructorOptions = array();
private $constructorTemplate = '
<script type="text/javascript">
FusionCharts.ready(function () {
new FusionCharts(__constructorOptions__);
});
</script>';
private $renderTemplate = '
<script type="text/javascript">
FusionCharts.ready(function () {
FusionCharts("__chartId__").render();
});
</script>
';
// constructor
function __construct($type, $id, $width = 400, $height = 300, $renderAt, $dataFormat, $dataSource) {
isset($type) ? $this->constructorOptions['type'] = $type : '';
isset($id) ? $this->constructorOptions['id'] = $id : 'php-fc-'.time();
isset($width) ? $this->constructorOptions['width'] = $width : '';
isset($height) ? $this->constructorOptions['height'] = $height : '';
isset($renderAt) ? $this->constructorOptions['renderAt'] = $renderAt : '';
isset($dataFormat) ? $this->constructorOptions['dataFormat'] = $dataFormat : '';
isset($dataSource) ? $this->constructorOptions['dataSource'] = $dataSource : '';
$tempArray = array();
foreach($this->constructorOptions as $key => $value) {
if ($key === 'dataSource') {
$tempArray['dataSource'] = '__dataSource__';
} else {
$tempArray[$key] = $value;
}
}
$jsonEncodedOptions = json_encode($tempArray);
if ($dataFormat === 'json') {
$jsonEncodedOptions = preg_replace('/\"__dataSource__\"/', $this->constructorOptions['dataSource'], $jsonEncodedOptions);
} elseif ($dataFormat === 'xml') {
$jsonEncodedOptions = preg_replace('/\"__dataSource__\"/', '\'__dataSource__\'', $jsonEncodedOptions);
$jsonEncodedOptions = preg_replace('/__dataSource__/', $this->constructorOptions['dataSource'], $jsonEncodedOptions);
} elseif ($dataFormat === 'xmlurl') {
$jsonEncodedOptions = preg_replace('/__dataSource__/', $this->constructorOptions['dataSource'], $jsonEncodedOptions);
} elseif ($dataFormat === 'jsonurl') {
$jsonEncodedOptions = preg_replace('/__dataSource__/', $this->constructorOptions['dataSource'], $jsonEncodedOptions);
}
$newChartHTML = preg_replace('/__constructorOptions__/', $jsonEncodedOptions, $this->constructorTemplate);
echo $newChartHTML;
}
// render the chart created
// It prints a script and calls the FusionCharts javascript render method of created chart
function render() {
$renderHTML = preg_replace('/__chartId__/', $this->constructorOptions['id'], $this->renderTemplate);
echo $renderHTML;
}
}
?>
Inside the rank_chart.php file.
<?php
require_once('database.php');
// Form the SQL query that returns.
$strQuery = "SELECT `rank_code`, COUNT(*) AS rank_cnt FROM `personel` WHERE rank_code!='' GROUP BY rank_code ORDER BY rank_code='2/LT',rank_code='LT',rank_code='CAPT',rank_code='MAJOR',rank_code='LT COL',rank_code='COL',rank_code='BRIG',rank_code='MAJ GEN',rank_code='LT GEN'";
// Execute the query, or else return the error message.
$result = $conn->query($strQuery);
// If the query returns a valid response, prepare the JSON string
if ($result) {
// The `$arrData` array holds the chart attributes and data
$arrData = array(
"chart" => array(
"caption"=> "",
"xAxisname"=> "Officer Ranks",
"yAxisName"=> "Number of Personnel",
"plotFillAlpha"=> "80",
"paletteColors"=> "#0075c2,#0e948c",
"baseFontColor"=> "#333333",
"baseFont"=> "Helvetica Neue,Arial",
"captionFontSize"=> "14",
"subcaptionFontSize"=> "14",
"subcaptionFontBold"=> "0",
"showBorder"=> "0",
"bgColor"=> "#ffffff",
"showShadow"=> "0",
"canvasBgColor"=> "#ffffff",
"canvasBorderAlpha"=> "0",
"divlineAlpha"=> "100",
"divlineColor"=> "#999999",
"divlineThickness"=> "1",
"divLineIsDashed"=> "1",
"divLineDashLen"=> "1",
"divLineGapLen"=> "1",
"usePlotGradientColor"=> "0",
"showplotborder"=> "0",
"valueFontColor"=> "#ffffff",
"placeValuesInside"=> "1",
"showHoverEffect"=> "1",
"rotateValues"=> "1",
"showXAxisLine"=> "1",
"xAxisLineThickness"=> "1",
"xAxisLineColor"=> "#999999",
"showAlternateHGridColor"=> "0",
"legendBgAlpha"=> "1",
"legendBorderAlpha"=> "0",
"legendShadow"=> "0",
"legendItemFontSize"=> "10",
"legendItemFontColor"=> "#666666"
)
);
$arrData["data"] = array();
// Push the data into the array
while($row = mysqli_fetch_array($result)) {
array_push($arrData["data"], array(
"label" => $row["rank_code"],
"value" => $row["rank_cnt"]
)
);
}
/*JSON Encode the data to retrieve the string containing the JSON representation of the data in the array. */
$jsonEncodedData = json_encode($arrData);
/*Create an object for the column chart using the FusionCharts PHP class constructor. Syntax for the constructor is ` FusionCharts("type of chart", "unique chart id", width of the chart, height of the chart, "div id to render the chart", "data format", "data source")`. Because we are using JSON data to render the chart, the data format will be `json`. The variable `$jsonEncodeData` holds all the JSON data for the chart, and will be passed as the value for the data source parameter of the constructor.*/
$columnChart = new FusionCharts("column2d", "Rank Chart" , "100%", "100%", "chart-1", "json", $jsonEncodedData);
// Render the chart
$columnChart->render();
// Close the database connection
}
?>

Related

Javascript/PHP - Reordering JSON array randomly causes null value and deletes everything

I have a random issue while trying to reorder items in a JSON array via JS/PHP, this occurs when the array has more than 1000 items.
Example of my Users.json file:
[
{
"ID_id": "123abc",
"ST_username": "johndoe",
"ST_email": "j#example.com",
"ST_fullname": "John Doe",
},
{
"ID_id": "def345",
"ST_username": "sarahdoe",
"ST_email": "s#example.com",
"ST_fullname": "Sarah Doe",
},
{
"ID_id": "fgh567g",
"ST_username": "markdoe",
"ST_email": "mark#example.com",
"ST_fullname": "Mark Doe",
}
// + additional 1000 similar items in this array
]
So, first of all, I get the JSON file's data and decode it into a PHP array:
$tableName = $_GET['tableName']; // Lets' say $tableName is 'Users'
// fetch data from 'Users.json'
$data = file_get_contents($tableName. '.json');
$data_array = json_decode($data, true);
Then I call this function in JS:
function reorderTableData() {
var newOrderArray = [];
var data_arrayStr = JSON.stringify(<?php echo json_encode($data_array) ?>);
var jsonData = JSON.parse(data_arrayStr);
var reorderedData = JSON.stringify(jsonData, newOrderArray);
$.ajax({
url : "reorder-table-data.php",
type: 'POST',
data: 'tableName='+'<?php echo $tableName ?>'+'&reorderedData='+encodeURIComponent(reorderedData),
success: function(data) {
location.reload();
// error
}, error: function(e) {
}});
}
}
My reorder-table-data.php code:
$tableName = $_POST['tableName'];
$reorderedData = $_POST['reorderedData'];
$data_array = json_decode($reorderedData, true);
// Encode back to JSON
$data = json_encode(array_values($data_array), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
file_put_contents($tableName. '.json', $data);
// echo JSON object
echo json_encode($data);
?>
Sometimes this code erases everything and all you see is null in the Users.json file, all data got lost.
What am I doing wrong?

Display get dynamic data in Chart.js with PHP and JS

I want to dynamically display statistics with Chart.js on my page from different users.
I can already display data with a clear data query from one user, but several identical bootstrap cards with different data should be displayed. How can I pass the user variables dynamicly to the mysqli_query in playerOne.php?
playerOne.php
header('Content-Type: application/json');
include "../../../includes/db.php";
$query = "SELECT SUM(game_stats.match_stats_kills) AS Kills, SUM(game_stats.match_stats_deaths) AS Deaths FROM game_stats WHERE game_stats.user_id = 1";
$select_kd = mysqli_query($connection, $query);
$data = array();
foreach($select_kd as $row) {
$data[] = $row;
}
mysqli_close($connection);
echo json_encode($data);
stats.js
$(document).ready(function() {
showData();
});
function showData() {
{
($.post("includes/stats/playerOne.php",
function(data) {
var kills = [];
var deaths = [];
for(var i in data) {
kills.push(data[i].Kills)
deaths.push(data[i].Deaths);
}
var pieChartData = {
labels: [
'Kills', 'Deaths'
],
datasets: [
{
backgroundColor: ['#f56954', '#00c0ef'],
data: [kills, deaths]
}
]
};
var pieChartTarget = $('#playerKD').get(0).getContext('2d');
var pieChart = new Chart(pieChartTarget, {
type: 'pie',
data: pieChartData
});
}));
}
}
you can send the variable on the url, here...
($.post("includes/stats/playerOne.php?user=1", // <-- add variable here -- ?user=1
then in your php, access the value of the variable using...
$_GET['user']
e.g.
$query = "SELECT SUM(game_stats.match_stats_kills) AS Kills, SUM(game_stats.match_stats_deaths) AS Deaths FROM game_stats WHERE game_stats.user_id = " + $_GET['user'];

Why can't I access the data in my JSON?

My PHP is:
if(!empty($_POST)&&($_POST['action']=='edit'))
{
foreach ($_POST['selected'] as $edit_id)
{
$query = "SELECT * FROM grocery WHERE id = $edit_id";
$result = dbQuery($query);
break;
}
$rowArr=array();
$inRow = mysqli_fetch_array($result);
$id = $inRow['id'];
$shop = $inRow['shop'];
$category = $inRow['category'];
$item = $inRow['item'];
$qnty = $inRow['quantity'];
$unit = $inRow['unit'];
$price_based_on = $inRow['price_based_on'];
$mrp = $inRow['MRP'];
$sellers_price = $inRow['sellers_price'];
$last_updated_on = $inRow['last_updated_on'];
array_push($rowArr, array('id' => $id, 'shop' => $shop, 'category' =>$category, 'item' => $item, 'qnty' => $qnty, 'unit' => $unit, 'price_based_on' => $price_based_on, 'mrp' => $mrp, 'sellers_price' => $sellers_price, 'last_updated_on' => $last_updated_on));
echo json_encode(array('rowArr' => $rowArr));
}
The output (JSON) produced by the above script is: (I've ensured this is produced in the Chrome's console)
{
"rowArr": [
{
"id": "30",
"shop": "Subhash",
"category": "Spices",
"item": "Duta Corriander Powder",
"qnty": "50",
"unit": "gm",
"price_based_on": "Packet",
"mrp": "15.00",
"sellers_price": "12.00",
"last_updated_on": "2016-12-03"
}
]
}
My jQuery is:
$('#edit').click(function(){
var data = $("#list :input").serialize();
$.post($("#list").attr('action'), data, function(json)
{
if(json.rowArr.length>0)
console.log("Data Exists");
else
console.log("Empty");
currentRow = json.rowArr[0];
console.log(json.rowArr[0].id);
$("#id").val(currentRow.id);
$("#id_disp").val(currentRow.id);
});
});
Strangely enough, neither Data Exists or Empty is produced by the above loop. And when I try to access the JSON data, json.rowArr[0].id I get the following error:
Uncaught TypeError: Cannot read property 'length' of undefined
Why is this happening? How do I fix it?
You should explicitly tell jQuery that your response has JSON format. You should pass 'json' as fourth argument of $.post, according to docs.
$('#edit').click(function(){
var data = $("#list :input").serialize();
$.post($("#list").attr('action'), data, function(json) {
if(json.rowArr.length>0)
console.log("Data Exists");
else
console.log("Empty");
currentRow = json.rowArr[0];
console.log(json.rowArr[0].id);
$("#id").val(currentRow.id);
$("#id_disp").val(currentRow.id);
}, 'json');
});

Google chart not getting printed in a loop

I've to show a Google Chart in a loop . Without loop my chart works fine but when i try to add it in a loop i get it only for first iterataion , how do i fix it , please review this
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Daily Report'],
['Points Achieved', <?php echo $points_achieved?>],
['Points Left', <?php echo $points_left?>]
]);
var options = {
backgroundColor: 'transparent',
title: '' ,
chartArea:{right:0,top:0,width:"90%",height:"100%" }
,height: 150
,width: 200,
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
<?php
$sql= "SELECT * FROM employees";
$query= mysqli_query($connection, $sql);
while($res= mysqli_fetch_assoc($query)): ?>
<div id='piechart'></div>
//other data from database comes here
<?php endwhile;?>
Since you are drawing multiple charts i would suggest to modify drawChart function to accept chart id and data as parameters:
function drawChart(chartId,data) {
var dataTable = google.visualization.arrayToDataTable(data);
var options = {
backgroundColor: 'transparent',
title: '' ,
chartArea:{right:0,top:0,width:"90%",height:"100%" },
height: 150
,width: 200,
};
var chart = new google.visualization.PieChart(document.getElementById(chartId));
chart.draw(dataTable, options);
}
Then you could iterate PHP array and invoke drawChart function:
<?php
foreach ($reports as $key => $report) {
$chartId = "piechart_$key";
//prepare chart data
$chartData = array(
array("Task", "Daily Report"),
array("Points Achieved" , $report["Points Achieved"]),
array("Points Left" , $report["Points Left"])
);
?>
<div id='<?php echo $chartId; ?>'></div>
<script type="text/javascript">drawChart('<?php echo $chartId; ?>',<?php echo json_encode($chartData); ?>)</script>
<?php
}
?>
It is assumed $reports array has the following structure:
//input data example ( replace it with data retrieved from DB)
$reports = array(
"R1" => array("Points Achieved" => 20, "Points Left" => 4),
"R2" => array("Points Achieved" => 40, "Points Left" => 14),
"R3" => array("Points Achieved" => 10, "Points Left" => 0)
);
Working example

Insert tag “series:” into Highcharts, from the response server JSON. Malformed JSON?

This is my second question about this problem:
I try to create a chart with Highcharts, but I can not fill the field "series" with the response returned from the server with PHP. The answer is in JSON format. The chart is not rendered, it goes white background. Thank you very much in advance.
I paste her the 3 codes:
SERVER SIDE PHP:
$arr = array();
while ($row_RecordsetTabla = mysql_fetch_assoc($RecordsetTabla))
{
$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");
$arr[] = array("Date.UTC(".$arregloFecha.",".$arregloHora.")", $estado);
}
$arr2[] = array('data' => $arr);
$json = json_encode($arr2);
echo str_replace('"', '', $json);
RESPONSE SERVER JSON:
[{data:[[Date.UTC(2014,03,27,12,00),2],[Date.UTC(2014,04,01,19,10),1],[Date.UTC(2014,04,01,15,44),1]]}]
CLIENT SIDE JAVASCRIPT HIGHCHARTS CODE:
$.get("mostrarStatsDispositivo.php", {idDispositivo:"2", numeroDispositivo:"hola"}, function(data){
chart = new Highcharts.Chart({
chart: {
renderTo: 'divStatsDispositivo',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'Gráfica de actividad'
},
tooltip: {
enabled: false,
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats : {
hour: '%H',
}
},
yAxis: {
categories: [ 'APAGADO', 'ACTIVO', 'ALARMA'],
title: {
text: 'ESTADO'
},
min: 0
},
series : [{
name : 'grafica',
type : 'line',
data : data[0].data //<-------thanks Barbara!
}]
});
});
The response JSON seems well formed..but dosn´t work...?¿ ....thanks!
EDIT: If i copy/paste the content of JSON in a variable, works fine. But i can´t put the value of JSON in a variable! ...doesn´t works! it´s posible?¿
FIXED!!!
Thanks Mr Jerko has detected (and solved) some errors in the code:
There is an error in a line of PHP file:
I put:
$arr2[] = array('data' => $arr);
and correct line is:
$arr2 = array('data' => $arr);
Another error to create a JSON line, and another error to put the data on "series:". check the responde under!
change your php file to look like this:
$arr = array();
while ($row_RecordsetTabla = mysql_fetch_assoc($RecordsetTabla))
{
$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");
$date = strtotime($arregloFecha . " " . $arregloHora) * 1000;
$arr[] = array($date, floatval($estado));
}
$arr2 = array('data' => $arr);
echo json_encode($arr2);
your JSON was in incorrect format because when you return Date.UTC(2014,03,27,12,00) without quotes it breaks format of json so you should convert your times to microseconds in php before echoing it.
also you would probably need to change your javascript line to
data: data.data

Categories

Resources