Manage multiple highchart charts in a single webpage with PHP - php

In my page, i have an options to choose if i want to show one chart or all chart, in the same time.
When i choose all chart to view, it's OK.
When i choose "chart a" it's OK.
When i choose "chart b" it does'n show any chart.
I remark that when i choose "chart a" or all charts, it display the both alert.
When i choose "chart b", it display only the first alert.
Am I doing something wrong?
Any help will be much appreciated.
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="http://code.highcharts.com/highcharts.js"></script>
<script type="text/javascript">
$(document).ready(function() {
Highcharts.setOptions({
chart: {
defaultSeriesType: 'spline',
},
xAxis: {
type: 'datetime',
},
});
var options1 = {
chart: {
renderTo: ''
},
series: []
};
var options2 = {
chart: {
renderTo: ''
},
series: []
};
alert("chart1");
options1.series.push({name: "Temperatura",data: _VARS['data1'],lineWidth: 1,color: '#3e5bc1'});
options1.chart.renderTo = 'chart_1';
var chart1 = new Highcharts.Chart(options1);
alert("chart2");
options2.series.push({name: "HR",data: _VARS['data2'],lineWidth: 1,color: '#3e5bc1'});
options2.chart.renderTo = 'chart_2';
var chart2 = new Highcharts.Chart(options2);
});
</script>
</head>
<body>
<script>
var _VARS = new Array();
_VARS['data1'] = [[Date.UTC(2012,7,14,12,0),26.1],[Date.UTC(2012,7,14,13,0),27.2],[Date.UTC(2012,7,14,14,0),28],[Date.UTC(2012,7,14,15,0),28.4],[Date.UTC(2012,7,14,16,0),27.1],[Date.UTC(2012,7,14,17,0),27.2],[Date.UTC(2012,7,14,18,0),26.1],[Date.UTC(2012,7,14,19,0),24.8],[Date.UTC(2012,7,14,20,0),22.5],[Date.UTC(2012,7,14,21,0),21.3],[Date.UTC(2012,7,14,22,0),20.1],[Date.UTC(2012,7,14,23,0),19],[Date.UTC(2012,7,15,0,0),18.3]];
VARS_AMBIENTE['data2'] = [[Date.UTC(2012,7,14,12,0),43],[Date.UTC(2012,7,14,13,0),44.1],[Date.UTC(2012,7,14,14,0),46.8],[Date.UTC(2012,7,14,15,0),49.3],[Date.UTC(2012,7,14,16,0),60.1],[Date.UTC(2012,7,14,17,0),57],[Date.UTC(2012,7,14,18,0),60.7],[Date.UTC(2012,7,14,19,0),69.5],[Date.UTC(2012,7,14,20,0),77.8],[Date.UTC(2012,7,14,21,0),80.5],[Date.UTC(2012,7,14,22,0),81.4],[Date.UTC(2012,7,14,23,0),83.1],[Date.UTC(2012,7,15,0,0),85.3]];
</script>
<h2>Choose Chart Test</h2>
<?php
// when i choose a, it's OK
// when i choose b, it's NOT OK
// when i choose c, it's OK
//$param ="a";
$param ="b";
//$param ="c";
if($param == 'a'){
echo "<p>chart a</p>
<div id='chart_1'></div>";
}elseif($param == 'b'){
echo "<p>chart b</p>
<div id='chart_2'></div>";
}else{
echo "all charts\n";
echo "<p>chart a</p><div id='chart_1' ></div></br></br>";
echo "<p>chart b</p><div id='chart_2'></div></br></br>";
}
?>
</body>
</html>

When you have chosen option b) the line:
var chart1 = new Highcharts.Chart(options1);
cause an error in javascript and the execution of the script is stopped. Highcharts could not find a chart_1 div and exits with error. When you choose option a) script go through this line but stops on this line:
var chart2 = new Highcharts.Chart(options2);
and you even do not notice this. Check in developer tools (Chrome or Firefox), there is an error in javascript console. I did it and in situation b) there is and error: Highcharts Error #13: Rendering div not found
To get it right you should check whether each of divs exists in html. Try using jQuery for this:
alert("chart1");
options1.series.push({name: "Temperatura",data: _VARS['data1'],lineWidth: 1,color: '#3e5bc1'});
options1.chart.renderTo = 'chart_1';
// checking if div#chart_1 exists
if ($("#chart_1").length > 0) {
var chart1 = new Highcharts.Chart(options1);
}
alert("chart2");
options2.series.push({name: "HR",data: _VARS['data2'],lineWidth: 1,color: '#3e5bc1'});
options2.chart.renderTo = 'chart_2';
// checking if div#chart_2 exists
if ($("#chart_2").length > 0) {
var chart2 = new Highcharts.Chart(options2);
}

Related

Looking for a way to get data from a google chart into php variable

I have cretae a column chart using Google chart which display a aggregate value. I've add a listener to enable some action when a column is selected.
The listener works as the alert statement displays the element I'd like to use.
How can I save into a php variable the selected item.
I looking for the code to be added in the pp section at the bottom of the display code below .
<div id="chart_div" style="height:400px;width:450px"></div>
<script type="text/javascript">
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
["SousCat_Nom", "Valeur", { role: "style" } ],
<?php
while($row4 = mysqli_fetch_array($resultAll))
{
echo "['".$row4["SousCat_Nom"]."', ".$row4['Valeur']." ,'#4d5ae3'],";
}
?>
]);
var options = {
chart: {
title: 'Dépenses par catégories ',
}
};
var chart = new google.charts.Bar(document.getElementById('chart_div'));
chart.draw(data, google.charts.Bar.convertOptions(options));
chart.draw(data, options);
google.visualization.events.addListener(chart, 'select', selectHandler);
function selectHandler() {
var selectedItem = chart.getSelection()[0,0];
if (selectedItem) {
var value = data.getValue(selectedItem.row, 0);
alert('The user selected ' + value);
<?php
// $data = ?????? ;
?>
}
}
}
</script>

Google combo chart issue

I am trying to create a combo chart using google charts,
in HTML added below CDN and div
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div" style="width: auto; height: 500px;"></div>
the result of
var examname = <?php echo json_encode($examnames); ?>;
var highestScore = <?php echo json_encode($heighestScores); ?>;
var userScore = <?php echo json_encode($userScores); ?>;
is
var examname = ["Test Name 1", "Full Test", "Knowledge"];
var highestScore = ["8", "11", "10"];
var userScore = ["6", "11"];
google.charts.load('current', {
'packages': ['corechart']
});
google.charts.setOnLoadCallback(drawVisualization);
function drawVisualization() {
// Some raw data (not necessarily accurate)
var graphData = new google.visualization.DataTable();
graphData.addColumn('string', 'TestName');
graphData.addColumn('number', 'Height');
graphData.addColumn('number', 'YourScore');
for (var i = 0; i < examname.length; i++) {
if (userScore[i] === undefined) {
userScore[i] = 0;
}
console.log(userScore[i]);
graphData.addRow(examname[i], {
v: highestScore[i],
f: userScore[i]
});
}
//graphData = graphData.replace(/'/g, '"');
//var data = google.visualization.arrayToDataTable(graphData);
console.log(data);
var options = {
title: 'Score Dashboard',
vAxis: {
title: 'Score'
},
hAxis: {
title: 'Exam Name'
},
seriesType: 'bars',
series: {
5: {
type: 'line'
}
}
};
var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart.draw(graphData, options);
}
JSFIDDLE
I am getting an error:
Error: If argument is given to addRow, it must be an array, or null
even I searched in google but I didn't understand. Please could any one help me to resolve the issue.
Your passing (string, object). When it's expecting just (array).
Change
graphData.addRow(examname[i], {
v: highestScore[i],
f: userScore[i]
});
To
graphData.addRow([
examname[i],
Number(highestScore[i]),
Number(userScore[i])
]);
Working example: https://jsfiddle.net/g4vjvam9/
Note: If you want the last column filled, you need to add the value :/
var userScore = ["6", "11", "2"];
Also avoid strings else your need to use Number() like above.

Highcharts doesn't update from file

I use Highcharts and when I update the site it doesn't update the data from which it constructs the graph.
I take the data from mysql, save it in a .csv file and open the .csv in highcharts. It seems to save the old values in the graph even if the .csv file is updated.
<?php
unlink('column-data.csv'); //This file must exist or else it gives error
include 'database.php';
$result = mysql_query("SELECT
value
FROM
data
INTO OUTFILE 'C:/xampp/htdocs/arduinoproj/test3/column-data.csv'
FIELDS ENCLOSED BY '\,'
TERMINATED BY ';'
ESCAPED BY '\"'
")
or die("Could not issue MySQL query");
include 'highcharts.php'
?>
..and the highcharts code is more or less unchanged.
The changed code from the original is in bold.
Highcharts code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>My first column chart by Highcharts</title>
<!-- 1. Add JQuery and Highcharts in the head of your page -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<!-- 2. You can add print and export feature by adding this line -->
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<!-- 3. Add the JavaScript with the Highchart options to initialize the chart -->
<script type="text/javascript">
jQuery(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
**type: 'line'**
},
title: {
text: 'Tiny Tool Monthly Sales'
},
subtitle: {
text: '2014 Q1-Q2'
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Sales'
}
},
series: []
};
// JQuery function to process the csv data
$.get(**'column-data.csv'**, function(data) {
// Split the lines
var lines = data.split('\n');
$.each(lines, function(lineNo, line) {
var items = line.split(',');
// header line contains names of categories
if (lineNo == 0) {
$.each(items, function(itemNo, item) {
//skip first item of first line
if (itemNo > 0) options.xAxis.categories.push(item);
});
}
// the rest of the lines contain data with their name in the first position
else {
var series = {
data: []
};
$.each(items, function(itemNo, item) {
if (itemNo == 0) {
series.name = item;
} else {
series.data.push(parseFloat(item));
}
});
options.series.push(series);
}
});
//putting all together and create the chart
var chart = new Highcharts.Chart(options);
});
});
</script>
</head>
<body>
<!-- 3. Add the container -->
<div id="container" style="width: 600px; height: 400px; margin: 0 auto"></div>
</body>
</html>

amCharts js doesnt work with ajax call?

I am trying create map with amCharts using jquery ajax but it doesnt work with ajax.
here my ajax code:
$('button#btn').click(function(){
$('div#ozellikli').html('<center><img src="assets/img/loading.gif" width="200" height="200"/></center>')
$.ajax({
type:'post',
url:'ozellikliAjax.php',
data:$('form#oz').serialize(),
success:function(msg){
$('div#ozellikli').html(msg);
}
});
});
Here my ajax php code:
<?php
include 'config.php';
$html="";
$yil=$_POST['yil'];
$tur=$_POST['tur'];
///HARITAYI CIZ
$sql="SELECT id,il,COUNT(kurum) AS kurum_Say FROM ozellikli GROUP BY id,il ORDER BY kurum_Say";
$result=$baglanti->query($sql);
$mapChart="";
while ($query=$result->fetch(PDO::FETCH_ASSOC)) {
$mapChart.=' { title: "'.$query['il'].':'.$query['kurum_Say'].'", id: "TR'.$query['id'].'",value:'.$query['kurum_Say'].', selectable: true },';
}
$html.='<script type="text/javascript">
AmCharts.ready(function() {
var map;
// *** CREATE MAP ***********************************************************
function createMap(){
map = new AmCharts.AmMap();
map.pathToImages = "http://www.ammap.com/lib/images/";
//map.panEventsEnabled = true; // this line enables pinch-zooming and dragging on touch devices
var dataProvider = {
mapVar: AmCharts.maps.turkeyLow
};
map.areasSettings = {
unlistedAreasColor: "#43B1A9",
rollOverOutlineColor: "#FFFFFF"
};
map.colorSteps=5;
map.valueLegend={
left: 10,
bottom:0,
minValue: "En Az",
maxValue: "En Çok"
};
dataProvider.areas = ['.$mapChart.'];
map.dataProvider = dataProvider;
map.addListener(\'clickMapObject\', function (event) {
// deselect the area by assigning all of the dataProvider as selected object
map.selectedObject = map.dataProvider;
// toggle showAsSelected
event.mapObject.showAsSelected = !event.mapObject.showAsSelected;
// bring it to an appropriate color
map.returnInitialColor(event.mapObject);
var states = [];
for (var i in map.dataProvider.areas) {
var area = map.dataProvider.areas[i];
if (area.showAsSelected) {
states.push(area.title);
}
}
});
map.write("mapdiv");
}
createMap();
});
</script>';
echo $html;
?>
when run the ajax code , script loading with ajax correctly but its not charting to map.
How can I solve this issue?
thanks
If you inject the resources the same way, you need to set manually it's ready state otherwise it won't work. AmCharts listens to the dom loaded event to set following property:
AmCharts.isReady = true;

PHP code and 2 While calling the same query

I need some help. I have some info in my db that I want to show in 2 charts using Google charts script.
Both scripts works but not when I use both scripts in a same page.. I bet is a problem with the while that are both equals since I need to show the same info. If I delete the first while the second loop start to work, but if no, the first just work.
The app works well because if I hardcode the values by hand and without the while works well both..
Here's the code:
<!-- First Chart start here: -->
<script type="text/javascript">
google.load("visualization", "1", {
packages: ["corechart"]
});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Formato', 'Cantidad'], <? php
//da problema si hay 2 while
while ($DatRDV = mysql_fetch_array($nrollos)) {
echo "['".$DatRDV['Formato'].
"',".$DatRDV['nRollos'].
"],";
} ?> ]);
var options = {
title: 'Formato de Rollos'
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<!-- Second chart start here: -->
<script type="text/javascript">
function drawVisualization() {
// Create and populate the data table.
var JSONObject = {
cols: [{
id: 'format',
label: 'Formato',
type: 'string'
}, {
id: 'cantidad',
label: 'Cantidades',
type: 'number'
}],
rows: [
<? php
while ($DatRDV = mysql_fetch_array($nrollos)) {
echo "{c:[{v: '".$DatRDV['Formato'].
"'}, {v: ".$DatRDV['nRollos'].
"}]},";
} ?> ]
};
var data = new google.visualization.DataTable(JSONObject, 0.5);
// Create and draw the visualization.
visualization = new google.visualization.Table(document.getElementById('table'));
visualization.draw(data, {
'allowHtml': true
});
}
google.setOnLoadCallback(drawVisualization);
</script>
try;
mysql_data_seek($nrollos,0);
before the 2nd loop

Categories