PHP code and 2 While calling the same query - php

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

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>

how to show a graph in each row in usgin googlechart(or chart.js etc)

I've been trying to display a graph in each row inside one page using Google chart but
I have no idea how to do that.
I get data from database when making a graph.
putting aside if this code below is right, here's my image.
#foreach ($titles as $title)
{{$title->title_name}}
<?php $getData = App\Graph::getNumber($title->id)?>
<div id="graph_bar{{$title->id}}" ></div> ←graph
#endforeach
<script type="text/javascript">
var barA= #json($getData->numberA);
var barB = #json($getData->numberB);
var barC= #json($getData->numberC);
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawchart);
function drawchart() {
var data = google.visualization.arrayToDataTable([
['', '', '', ''],
['', barA, barB , barC],
]);
var options = {
isStacked: true,
isStacked:'percent',
legend: {position: 'none'},
series: {
0:{color:'red'},
1:{color:'blue'},
2:{color:'grey'},
}
};
var chart = new google.visualization.BarChart(document.getElementById('graph_bar'));
chart.draw(data, options);
}
$(window).resize(function(){
drawchart();
});
</script>
1.Is it possible to do that(display a graph in each row) in the first place?
2.I'd like to get ID from HTML at javascript.
if anyone knows anything about this, I'd appreciate if if you would help me out.
thank you.

how to display google comparison chart vertically

in my project i need to show graph on particular place, i used to google bar charts for comparison, i get the graph but it appears on horizontally, but i need the graph in vertically, i tried from morning on wards but no luck, please help. Thanks in advance. Below is the my code
<script type="text/javascript">
google.charts.setOnLoadCallback(drawChart);
imagepath_comparison="";
function drawChart() {
var data = google.visualization.arrayToDataTable([<?=$data;?>]);
var options = {
title: 'GRAPH ANALYSIS',
vAxis: {title: "SUBJECTS"},
hAxis: {
title: "MARKS"
}
};
var chart3 = new google.visualization.BarChart (document.getElementById("columnchart_material"));
google.visualization.events.addListener(chart3, 'ready', function () {
imagepath_comparison=chart3.getImageURI();
drawChart1();
});
chart3.draw(data, options);
}
</script>
it was very simple thing need to change for displaying the results,i used ColumnChart in place of Barchart at that time my problem is solved.
my code after changing is
<script type="text/javascript">
google.charts.setOnLoadCallback(drawChart);
imagepath_comparison="";
function drawChart() {
var data = google.visualization.arrayToDataTable([<?=$data;?>]);
var options = {
title: 'GRAPH ANALYSIS',
vAxis: {title: "SUBJECTS"},
hAxis: {
title: "MARKS"
}
};
var chart3 = new google.visualization.BarChart (document.getElementById("columnchart_material"));
google.visualization.events.addListener(chart3, 'ready', function () {
imagepath_comparison=chart3.getImageURI();
drawChart1();
});
chart3.draw(data, options);
}
</script>

Manage multiple highchart charts in a single webpage with 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);
}

Passing PHP array into Javascript through JSON to update Google Chart

I have three PHP arrays that I've encoded with json... extra PHP code has been omitted because the arrays work properly.... Additionally, the HTML tags that call the google chart have been omitted for sake of brevity...
<?php
$encoded_line_volume = json_encode($LineVol) . "\n";
$encoded_loan_volume = json_encode($LoanVol) . "\n";
$encoded_cluster_name = json_encode($ClusterLine) . "\n";
?>
I would like to access these three arrays in Javascript to update my Google Chart dynamically.
<script type="text/javascript">
google.load("visualization", "1", {packages:["columnchart"]});
google.setOnLoadCallback(drawChart);
var linevol = new Array; // This would be the first array passed from PHP
var loanvol = new Array; // This would be the second array passed from PHP
var clusters = new Array; // This would be the third array passed from PHP
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Cluster');
data.addColumn('number', 'Loans');
data.addColumn('number', 'Lines');
/* create for loops to add as many columns as necessary */
var len = jsonarray.length;
data.addRows(len);
for(i=0; i<len; i++) {
data.setValue(i, 0, ' '+clusters[i]+''); /* x-axis */
data.setValue(i, 1, linevol[i]); /* Y-axis category #1*/
data.setValue(i, 2, loanvol[i]); /* Y-axis category #2*/
}
/*********************************end of loops***************************************/
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240, is3D: true, title: 'Prospect Population', legend: 'right'});
}
</script>
You probably want them to become Javascript variables. When your php executes, it creates code your web browser then interprets. So you want to define javascript strings using php. For example:
<script type="text/javascript">
var encoded_line_volume = <?php echo json_encode($LineVol) ?>;
var encoded_loan_volume = <?php echo json_encode($LoanVol) ?>;
var encoded_cluster_name = <?php echo json_encode($ClusterLine) ?>;
</script>
Then those variables are accessible to subsequent javascript.
This is how can you generate data dynamically from PHP, generate a JSON formatted output properly and read it from JavaScript (JQuery required) and load it to Google Visulization (Charts) API.
PHP (Server) Side:
function returnData() {
$data = Array ();
$data [] = Array ("Name", "Value");
$data [] = Array ("Apple", 5);
$data [] = Array ("Banana", 3);
header('content-type: application/json');
echo json_encode($data);
}
Javascript (Client) Side:
var jsonData = null;
var jsonDataResult = $.ajax({
url: dataURL,
dataType: "json",
async: false,
success: (
function(data) {
jsonData = data;
})
});
var data = new google.visualization.arrayToDataTable(jsonData);
This is one of the best examples I did which can help you : its tested and working nicely : Create two pages one called index.php and another one called get_json.php :
This is not exactly the codes you posted but exactly the same idea and it answers the quetion.
the codes for index.php
<html>
<head>
<title>King Musa Graph</title>
<!-- Load jQuery -->
<script language="javascript" type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js">
</script>
<!-- Load Google JSAPI -->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "get_json.php",
dataType: "json",
async: false
}).responseText;
var obj = jQuery.parseJSON(jsonData);
var data = google.visualization.arrayToDataTable(obj);
var options = {
title: 'King Musa'
};
var chart = new google.visualization.LineChart(
document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;">
</div>
</body>
</html>
codes for get_json.php
<?php
$data = Array ();
$data [] = Array ("Name", "Value");
$data [] = Array ("PHP", 78);
$data [] = Array ("JAVA", 1000);
$data [] = Array ("HTML", 129);
$table = json_encode($data);
// header('content-type: application/json');
echo $table ; // this line is important it should be not disabled
?>

Categories