Passing PHP array into Javascript through JSON to update Google Chart - php

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
?>

Related

how can i transform my josn_encode data in array into google bar chart?

This is my json_encoded data
$encoded_data = json_encode($data);
echo $encoded_data;
[{"cols":"2017-09-02 11:01:55","rows":"1186.55"},{"cols":"2017-09-03 11:31:35","rows":"1311.45"},{"cols":"2017-09-06 15:22:38","rows":"90000.00"},{"cols":"2017-09-06 16:39:16","rows":"90000.00"},{"cols":"2017-09-06 16:40:09","rows":"630.00"},{"cols":"2017-09-06 17:25:26","rows":"1311.45"},{"cols":"2017-09-06 17:54:50","rows":"1311.45"},{"cols":"2017-09-07 09:28:57","rows":"1311.45"},{"cols":"2017-09-07 10:20:16","rows":"1575.00"},{"cols":"2017-09-07 10:22:28","rows":"1311.45"},{"cols":"2017-09-07 10:27:52","rows":"1311.45"},{"cols":"2017-09-07 10:34:00","rows":"1311.45"},{"cols":"2017-09-07 10:39:46","rows":"91575.00"},{"cols":"2017-09-07 10:40:48","rows":"91311.45"},{"cols":"2017-09-07 10:47:34","rows":"1575.00"},{"cols":"2017-09-07 10:50:53","rows":"1575.00"},{"cols":"2017-09-07 10:51:18","rows":"1575.00"}]
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
// Load the Visualization API and the corechart package.
google.charts.load('visualization', '1', {'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 jsonData = <?php echo $encoded_data; ?>
var data = new google.visualization.DataTable(jsonData);
// Set chart options
var options = {'title':'sales chart',
'width':400,
'height':300};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
It gives me an error the table has no columns.
the json is not in the correct format to create the data table directly,
see the structure of the JavaScript literal object described here...
if you don't want to change the format, then it can be transformed using javascript
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
function drawChart() {
var jsonData = [{"cols":"2017-09-02 11:01:55","rows":"1186.55"},{"cols":"2017-09-03 11:31:35","rows":"1311.45"},{"cols":"2017-09-06 15:22:38","rows":"90000.00"},{"cols":"2017-09-06 16:39:16","rows":"90000.00"},{"cols":"2017-09-06 16:40:09","rows":"630.00"},{"cols":"2017-09-06 17:25:26","rows":"1311.45"},{"cols":"2017-09-06 17:54:50","rows":"1311.45"},{"cols":"2017-09-07 09:28:57","rows":"1311.45"},{"cols":"2017-09-07 10:20:16","rows":"1575.00"},{"cols":"2017-09-07 10:22:28","rows":"1311.45"},{"cols":"2017-09-07 10:27:52","rows":"1311.45"},{"cols":"2017-09-07 10:34:00","rows":"1311.45"},{"cols":"2017-09-07 10:39:46","rows":"91575.00"},{"cols":"2017-09-07 10:40:48","rows":"91311.45"},{"cols":"2017-09-07 10:47:34","rows":"1575.00"},{"cols":"2017-09-07 10:50:53","rows":"1575.00"},{"cols":"2017-09-07 10:51:18","rows":"1575.00"}];
var data = new google.visualization.DataTable();
data.addColumn('string', 'x');
data.addColumn('number', 'y');
jsonData.forEach(function (row) {
data.addRow([
row.cols,
parseFloat(row.rows)
]);
});
var options = {
title: 'sales chart',
width: 400,
height: 300,
chartArea: {
left: 140
}
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

sending array from php to jquery

how do i pass an array from php to jquery
both are in same file , i just have an array named $array2 with data that will be used to make graph
below code is using chartdata but i want to use variable from my php script
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
var chart;
var chartData = [{
student: 5,
marks: 0},
{
student: 8,
marks: 50},
{
student: 10,
marks: 100}];
AmCharts.ready(function() {
// SERIAL CHART
chart = new AmCharts.AmSerialChart();
chart.dataProvider = chartData;
chart.categoryField = "marks";
chart.startDuration = 1;
// AXES
// category
var categoryAxis = chart.categoryAxis;
categoryAxis.labelRotation = 90;
categoryAxis.gridPosition = "student";
// value
// in case you don't want to change default settings of value axis,
// you don't need to create it, as one value axis is created automatically.
// GRAPH
var graph = new AmCharts.AmGraph();
graph.valueField = "student";
graph.balloonText = "[[category]]: [[value]]";
graph.type = "column";
graph.lineAlpha = 0;
graph.fillAlphas = 8.4;
chart.addGraph(graph);
chart.write("chartdiv");
});
</script>
you can use json data to pass php to jquery.
in php
$php_data = json_encode($your_php_data_in_array);
assigning to jquery
var data = <?php echo $php_data ;?>
getting the value in jquery
var chart_data_arr = json_decode(data);
now you have the data in array in jquery.
The simplest (and not necessarily the most scure/efficient/modular/blah blah) possible way you can just dump it using json_encode
var chartData = [{
student: 5,
marks: 0},
{
student: 8,
marks: 50},
{
student: 10,
marks: 100}];
//Instead
var chartData=<?php echo json_encode($chartdata)?>
Alternately, you would pass it using a json action that will render the json at a certian link and use jquery to query this url and then generate the chart with that data.
To use php data in javascript use:-
var javascriptVariable = <?php echo json_encode($php_array); ?>;
So javascriptVariable would become an object/array as per your php data.
Try this :
<?php
$your_php_array = array(.....);
?>
var chartData = <?php json_encode($your_php_array)?>;
ref: http://php.net/manual/en/function.json-encode.php

Display a google chart with json & PHP

I'm trying to generate a google chart from mysql data using php.
Here is my code so far :
get_json.php
<?php
/* $server = the IP address or network name of the server
* $userName = the user to log into the database with
* $password = the database account password
* $databaseName = the name of the database to pull data from
* table structure - colum1 is cas: has text/description - column2 is data has the value
*/
$con = mysql_connect('localhost','root','') ;
mysql_select_db('gcm', $con);
// write your SQL query here (you may use parameters from $_GET or $_POST if you need them)
$query = mysql_query('SELECT count(name) As Subscribers,CAST(`created_at` AS DATE) As Date FROM gcm_users GROUP BY created_at ORDER BY created_at')or die(mysql_error());
$table = array();
$table['cols'] = array(
/* define your DataTable columns here
* each column gets its own array
* syntax of the arrays is:
* label => column label
* type => data type of column (string, number, date, datetime, boolean)
*/
// I assumed your first column is a "string" type
// and your second column is a "number" type
// but you can change them if they are not
array('label' => 'Date', 'type' => 'string'),
array('label' => 'Subscribers', 'type' => 'number')
);
$rows = array();
while($r = mysql_fetch_assoc($query)) {
$temp = array();
// each column needs to have data inserted via the $temp array
$temp[] = array('v' => $r['Date']);
$temp[] = array('v' => (int) $r['Subscribers']);
// insert the temp array into $rows
$rows[] = array('c' => $temp);
}
// populate the table with rows of data
$table['rows'] = $rows;
// encode the table as JSON
$jsonTable = json_encode($table);
// set up header; first two prevent IE from caching queries
header('Cache-Control: no-cache, must-revalidate');
header('Content-type: application/json');
// return the JSON data
echo $jsonTable;
?>
It displays right : {"cols":[{"label":"Date","type":"string"},{"label":"Subscribers","type":"number"}],"rows":[{"c":[{"v":"2013-04-14"},{"v":1}]},{"c":[{"v":"2013-04-15"},{"v":1}]}]}
This is where I display :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>
Google Visualization API Sample
</title>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['corechart']});
</script>
<script type="text/javascript">
function drawVisualization() {
var jsonData = null;
var json = $.ajax({
url: "get_json.php", // make this url point to the data file
dataType: "json",
async: false,
success: (
function(data) {
jsonData = data;
})
}).responseText;
// Create and populate the data table.
var data = new google.visualization.DataTable(jsonData);
// Create and draw the visualization.
var chart= new google.visualization.LineChart(document.getElementById('visualization')).
draw(data, {curveType: "function",
width: 500, height: 400,
vAxis: {maxValue: 10}}
);
}
google.setOnLoadCallback(drawVisualization);
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
<div id="visualization" style="width: 500px; height: 400px;"></div>
</body>
</html>
But when i run this code I got nothing,it's blank ! Where is my error?
Now tested:
You haven't included jQuery in your page. Add this line in your <head> and it works.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Another thing that can happen if your AJAX call takes a little longer:
By the time your success: function() is called after the AJAX call is finished the rest of the script has already run. The script doesn't wait until the AJAX call is finished until the "Create and populate" part is executed. You have to place these lines inside the success: function().
<script type="text/javascript">
function drawVisualization() {
var jsonData = null;
var json = $.ajax({
url: "get_json.php", // make this url point to the data file
dataType: "json",
async: false,
success: (
function(data) {
jsonData = data;
// Create and populate the data table.
var data = new google.visualization.DataTable(jsonData);
// Create and draw the visualization.
var chart= new google.visualization.LineChart(document.getElementById('visualization')).
draw(data, {curveType: "function",
width: 500, height: 400,
vAxis: {maxValue: 10}}
);
})
}).responseText;
}
google.setOnLoadCallback(drawVisualization);
</script>
This way you can make sure that all relevant code is only executed after the AJAX call has finished.

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

multiple highcharts on one page

I'm wishing to render multiple charts using mysql data, there will be more or less charts depending on a particular search. I've successfully created a single chart, and my php file echoes the required json format nicely.
Now, what I would like is to be able to loop over an array and draw new charts based on the array vales being parsed to the php which in turn provides different json data to be rendered.
by the way, my javasript is very limited so here goes my code and thoughts:
<script type="text/javascript">
$(function () {
var chart;
var venue = <?php echo json_encode($venue_name); ?>; /* parsed to php file */
var distances = <?php echo json_encode($data); ?>; /* array to be looped over */
$(document).ready(function() {
var options = {
....
series: []
....
};
//
$.each(distances, function() {
$.each(this, function(name, value) {
// do some ajax magic here:...
GET 'myphpfile.php?venue='+venue+'&'+distances
function drawNewChart(){
$('#mainSite').append('<div id="container" style="float:left; display:inline"></div>');
chart = new Highcharts.Chart(options);
});
});
</script>
What I have learnt is that I cannot loop an include php file which has the completed php and jquery...
this will create other charts. every time u want create new chart , u must give new name chart like i do chart2
paste this bellow and it will give you other chart.
<script type="text/javascript">
$(function () {
var chart2;
var venue2 = <?php echo json_encode($venue_name); ?>; /* <---use other variable here of $venue_name */
var distances2 = <?php echo json_encode($data); ?>; /* <---use other variable of $data */
$(document).ready(function() {
var options = {
....
series: []
....
};
//
$.each(distances2, function() {
$.each(this, function(name, value) {
// do some ajax magic here:...
GET 'myphpfile.php?venue2='+venue2+'&'+distances2
function drawNewChart(){
$('#mainSite').append('<div id="container" style="float:left; display:inline"></div>');
chart2 = new Highcharts.Chart(options);
});
});
</script>
Instead of using many variables, you can push your charts to array.
var charts = [];
charts.push(new Highcharts(options));
Then you can avoid of using index etc.

Categories