Google Line Charts interpolateNulls: false breaks chart - javascript

I knew the answer was going to be much simpler then I was making it out to be. I added the following if statement to the while loop.
<?php
echo "['Month', '$year1' , '$year2' , '$currentYear'],";
require('./PHPConnect.php');
$statement1 = #mysqli_query($dbc, $query1);
while($row = mysqli_fetch_array($statement1)){
if($row["Year3"] == NULL ? $row["Year3"] = 'null' : $row["Year3"] = $row["Year3"]);
echo "['".$row["Month"]."', ".$row["Year1"].", ".$row["Year2"].", ".$row["Year3"]."],";
}
mysqli_close($dbc);
?>
As an update we now know that the problem is MySql spits out NULL and javascript requires null. Any thoughts on how to accomplish getting MySql NULL int value into lowercase null.
*I was wondering if anyone can help me with this. I created a line chart to visual show company sales by month for the current year and the previous 2. It works fine, but because at this point there is 0 sales for the remaining months of the year it shows a steep drop off for that line. We don't want to see that, so I tried changing the 0s to nulls in the database and using interpolateNulls false. However when I add the interpolateNulls option the line chart breaks and no longer displays anything. Any ideas?
<script type="text/javascript">
var data;
var chart;
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart(){
data = google.visualization.arrayToDataTable([
<?php
echo "['Month', '$year1' , '$year2' , '$currentYear'],";
require('./PHPConnect.php');
$statement1 = #mysqli_query($dbc, $query1);
while($row = mysqli_fetch_array($statement1)){
echo "['".$row["Month"]."', ".$row["Year1"].", ".$row["Year2"].", ".$row["Year3"]."],";
}
mysqli_close($dbc);
?>
]);
var options = {
backgroundColor: 'transparent',
title:'Total Sales By Month',
width:600,
height:500,
interpolateNulls: false,
legend: {position: 'bottom'}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}

Related

How to pass PHP arrays to Google Graph JavaScript function?

I am trying to output the contents of two arrays as the axis for a chart using Google's chart API.
I currently output the JavaScript function using PHP, which is where I feel the error is. I believe the script is just getting output but not running. I can see it has output in the correct format from the page source, however, no data is being shown on the window.
The following is the contents of my two arrays, which are just key and value pairs in separate arrays:
The following is my code in the HTML body, which I call in PHP in the same page:
<?php
function createChart($nutrientArr, $percentArr) {
$chart = "<script type='text/javascript'>
google.charts.load('current', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Nutrient');
data.addColumn('number', 'Percentage Intake');
data.addRows(JSON.parse([";
for($i = 0;$i < count($nutrientArr);$i++) {
$chart .= "['" . $nutrientArr[$i] . "', '" . $percentArr[$i] . "'],";
if($i == count($nutrientArr) - 1) {
$chart .= "['" . $nutrientArr[$i] . "', '" . $percentArr[$i] . "']";
}
}
$chart .= "]));
// Set chart options
var options = {'title':'Daily Nutrient Intake (Percentage)',
'width':500,
'height':400};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>";
echo $chart;
}
?>
This is the source code:
<script type='text/javascript'>
google.charts.load('current', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Nutrient');
data.addColumn('number', 'Percentage Intake');
data.addRows(JSON.parse([['Calories', '18.32768'],['Fat', '23.065360824742'],['Saturated Fat', '22.640580645161'],['Monosaturated Fat', '25.274138888889'],['Polyunsaturated Fat', '23.481666666667'],['Carbohydrates', '8.6173573573574'],['Fiber', '17.975466666667'],['Sugar', '13.857878787879'],['Protein', '63.232972972973'],['Cholesterol', '37.102'],['Sodium', '7.8765666666667'],['Calcium', '13.39272'],['Magnesium', '20.481214285714'],['Potassium', '17.816553191489'],['Iron', '52.980375'],['Zinc', '25.689818181818'],['Phosphorus', '51.941142857143'],['Vitamin A', '13.804971428571'],['Vitamin C', '15.494555555556'],['Thiamin (B1)', '21.825333333333'],['Riboflavin (B2)', '23.152538461538'],['Niacin (B3)', '69.055'],['Vitamin B6', '63.236153846154'],['Folate Equivalent (Total)', '40.9758'],['Folate (Food)', '19.098075'],['Folic Acid', '0.8311225'],['Vitamin B12', '24.940875'],['Vitamin D', '2.1734733333333'],['Vitamin E', '13.491866666667'],['Vitamin K', '18.9045']]));
// Set chart options
var options = {'title':'Daily Nutrient Intake (Percentage)',
'width':500,
'height':400};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
I call the createChart() function in PHP at the top of the page, passing the two arrays.
I am looking to see what the best method of passing this data to the chart API is? Should I call the JS function from PHP and pass the arrays that way? I am not too familiar with JS so not sure how I would pass this data. Any help is very appreciated!
I have tried using json_encode and json_parse but neither work as I suspect I'm outputting the code at the wrong time or wrong way.

Undefined variable for a second query

I have an undefined Variable problem:
Effect on this first part of code everything works my variable $ id and well defined and works fine.
The cell_id is the result of a combobox which is then transmitted as an ajax on this page and it works fine
if(isset($_GET['cellule_id']) && !empty($_GET['cellule_id'])){
include('../../../connexion.php');
$id= $_GET['cellule_id'];
$query1 = pg_query($db,'SELECT ("T_CELLULE"."IDLocationEnCoursCellule"), COUNT(*) as qte_att_m
FROM "T_STATUT", "T_STATUT_CELLULE", "T_CELLULE", "T_OF"
WHERE ("T_STATUT_CELLULE"."SNCellule")=("T_CELLULE"."SNCellule")
AND ("T_STATUT"."IDStatut")=("T_STATUT_CELLULE"."IDStatut")
AND ("T_STATUT_CELLULE"."OF")=("T_CELLULE"."OF")
AND ("T_STATUT_CELLULE"."IDProcess")=("T_CELLULE"."IDProcess")
AND ("T_CELLULE"."OF"="T_OF"."OF")
AND ("T_CELLULE"."IDProcess"="T_OF"."IDProcess")
AND ("T_CELLULE"."RebutCellule" Is Null)
AND NOT("T_CELLULE"."IDLocationEnCoursCellule" Is Null)
AND ("T_CELLULE"."FinProcess" Is Null)
AND ("T_STATUT_CELLULE"."EnCours"=True)
AND ("T_STATUT"."IDStatut") = 2
AND ("T_OF"."TypeCellule")= \''. $id. '\'
GROUP BY "IDLocationEnCoursCellule"');
But when I want to display the result of my query in a js chart using google charts the problem comes from my query which is exactly the same but this time the $ id is not defined.
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['IDLocationEnCoursCellule','qte_att_m'],
<?php
$result = pg_query($db,'SELECT ("T_CELLULE"."IDLocationEnCoursCellule"), COUNT(*) as qte_att_m
FROM "T_STATUT", "T_STATUT_CELLULE", "T_CELLULE", "T_OF"
WHERE ("T_STATUT_CELLULE"."SNCellule")=("T_CELLULE"."SNCellule")
AND ("T_STATUT"."IDStatut")=("T_STATUT_CELLULE"."IDStatut")
AND ("T_STATUT_CELLULE"."OF")=("T_CELLULE"."OF")
AND ("T_STATUT_CELLULE"."IDProcess")=("T_CELLULE"."IDProcess")
AND ("T_CELLULE"."OF"="T_OF"."OF")
AND ("T_CELLULE"."IDProcess"="T_OF"."IDProcess")
AND ("T_CELLULE"."RebutCellule" Is Null)
AND NOT("T_CELLULE"."IDLocationEnCoursCellule" Is Null)
AND ("T_CELLULE"."FinProcess" Is Null)
AND ("T_STATUT_CELLULE"."EnCours"=True)
AND ("T_STATUT"."IDStatut") = 2
AND ("T_OF"."TypeCellule")= \''. $id. '\'
GROUP BY "IDLocationEnCoursCellule"');
while($row = pg_fetch_assoc($result)){
echo "['".$row['IDLocationEnCoursCellule']."',".$row['qte_att_m']."],";
}
?>
]);
var options = {
chart: {
title: 'test graphique',
subtitle: 'sous titre du test graphique',
}
};
var chart = new google.charts.Bar(document.getElementById('columnchart_material'));
chart.draw(data, google.charts.Bar.convertOptions(options));
}
</script>
<div id="columnchart_material"></div>
If I replace my $ id variable with a hard element it works but I have an undefined variable error
I tried a multitude of things:
- to put the $id= $_GET['cellule_id'];in the php just before my request
I've been there for 7 days on it
I can't figure out how a variable can be defined 30 lines above and then undefined thereafter.
thank you in advance good week everyone
leo

How to set Google Charts scales/intervals?

How can I set the intervals on Google Charts?
I don't know if that's how it's called, but, in the image, they are the 200k, 400k and so on.
Since some of my values are pretty small, I need to create intervals at each 5k or so.
How can I set this using Google Charts?
The code I'm using is down here:
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawChart4);
function drawChart4() {
var data = google.visualization.arrayToDataTable([
<?php echo $dados; ?>
]);
var options = {
chart: {title: <?php echo "'".str_replace('_', ' ', $subtitulo)."'" ?>,
},bars: 'horizontal',
width: 1250,
height: 350,
colors: ['#4c4c4c','#07bb27']
};
var chart = new google.charts.Bar(document.getElementById('column_horizontal'));
chart.draw(data, google.charts.Bar.convertOptions(options));
}

Adding date in the x-axis usig flot graph

The code I am using is below.
I want to make a simple graph based on the data from my database table.
It is working now but I want date on the bottom axis is not appearing properly.
while the value of variable is
[25-03-15, 1236], [26-03-15, 3000], [27-03-15, 3054], [30-03-15, 4000]
that is right. But I cant get this date on the x-axis. any solution there?
The way I am getting getting this value is
<?php
$usd=$this->db->query('select transaction_date, SUM(amount) as total from transactions GROUP BY transaction_date')->result_array();
$str = '';
for($i=0; $i<count($usd); $i++){
if($i!=0){
$str = $str.', ['.date('d-m-y', strtotime($usd[$i]["transaction_date"])).', '.$usd[$i]["total"].']';
}else{
$str = $str.'['.date('d-m-y', strtotime($usd[$i]["transaction_date"])).', '.$usd[$i]["total"].']';
}
}
echo $str;
?>
Then I pass this data in java script like this:
var graphData = [{
data: [ <?php echo $str; ?>]
}
];
But At the end I can not get the date on x axis.
PS:
I am working on the view of codeigniter application.
Have a look at the documentation for time series data.
You need javascript timestamps. In PHP you get them simply with
strtotime($usd[$i]["transaction_date"]) * 1000
Then your data should look like this:
[1427238000000, 1236], [1427324400000, 3000], ...
For the labels on the x axis, use the timeformat options to get back the format you want:
xaxis: {
mode: "time",
timeformat: "%d-%m-%y"
}

Converting this highcharts to my data

I would like to replicate this highcharts column graph: http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/column-drilldown/
I'm pulling my data from a table and it looks like this.
I want the Job_Num on the x-axis where brands are in the fiddle, PercentofBudgetedHrs would be the brandsData. Now when you click a job number, it drills down to departments and shows their percentage of budgeted hrs.
I have the first part working, but I'm using different code like so: http://jsfiddle.net/98Fuq/4/
Here is what I changed in that code:
$sql = "SELECT * FROM view_percentof_budgeted WHERE PercentofBudgetedHrs < 1000 && PercentofBudgetedHrs IS NOT NULL";
$result = mysqli_query($dbc3, $sql);
while($row = mysqli_fetch_assoc($result)) {
$jobNum[] = $row['Job_Num'];
$jobData[$row['Job_Num']] = $row['PercentofBudgetedHrs'];
$jobDrillData[$row['Job_Num']][] = $row;
}
The part I changed in the JS:
var colors = Highcharts.getOptions().colors,
categories = [<?php echo join($jobNum, ',') ?>],
name = '% of budgeted hours',
level = 0,
data = [
<?php echo join($jobData, ',') ?>,
];
function setChart(name, categories, data, color, level) {
chart.xAxis[0].setCategories(categories);
chart.series[0].remove();
chart.addSeries({
name: name,
data: data,
level: level,
color: color || 'red'
});
}
How do I go about doing it the way that first fiddle I posted does it? I like my method of pulling the data from a table so I don't want to use a tsv, I'm just confused on the drilldown part. I've looked at examples but can't seem to figure it out.
Instaed of using join() I advice to prepare correct strucutre of arrays in php, then use json_encode() including JSON_NUMERIC_CHECK flag. As a result you can get this json by $.getJSON and put in highcharts.

Categories