When i run the below I am getting TypeError: google.visualisation is undefined[Learn More]
the data is coming back from my .php file and I can see it when I do a console.log.
I am probably lost in with the callbacks or maybe someone can andvise otherwise?
I have tried to load the visualistion before i do my ajax here but same error. I have also looked at other possible answers but I still cannot get it to work.
This is my code:
$(document).ready(function(){
console.log("hello world")
//alert("result")
$.ajax({
url:"data.php",
dataType : "JSON",
success : function(result) {
google.charts.load('current', { 'packages':['corechart'] });
google.charts.setOnLoadCallback(function() {
console.log(result);
drawChart(result);
});
}
});
function drawChart(result) {
var data = new google.visualisation.Datatable();
data.addColumn('string','Name');
data.addColumn('number','Quantity');
var dataArray=[];
$.each(result, function(i, obj) {
dataArray.push([ obj.name, parseInt(obj.quantity) ]);
});
data.addRows(dataArray);
var piechart_options = {
title : 'Pie Chart: How Much Products Sold By Last Night',
width : 400,
height : 300
}
var piechart = new google.visualisation.PieChart(document
.getElementById('piechart_div'));
piechart.draw(data, piechart_options)
var barchart_options = {
title : 'Bar Chart: How Much Products Sold By Last Night',
width : 400,
height : 300,
legend : 'none'
}
var barchart = new google.visualisation.BarChart(document
.getElementById('barchart_div'));
barchart.draw(data, barchart_options)
}
});
I am getting an object back from my DB query, so I think that part is right, which is an array with 6 objects:
0: Object { id: "1", name: "Product1", quantity: "2" }
1: Object { id: "2", name: "Product2", quantity: "3" }
2: Object { id: "3", name: "Product3", quantity: "4" }
3: Object { id: "4", name: "Product4", quantity: "2" }
4: Object { id: "5", name: "Product5", quantity: "6" }
5: Object { id: "6", name: "Product6", quantity: "11" }
For what it is worth my php code is as follows:
data.php
<?php
require_once 'database.php';
$stmt = $conn->prepare('select * from product');
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_OBJ);
echo json_encode($results);
?>
database.php
<?php
$conn = new PDO('mysql:host=192.168.99.100;dbname=demo','root', 'root');
?>
Note: this version is similar but slightly different
you can actually use
google.charts.load
in place of
$(document).ready
and it should be with a z not s
visualization
not
visualisation
try it like this...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
$.ajax({
url:"data.php",
dataType : "JSON",
success : function(result) {
drawChart(result);
}
});
});
function drawChart(result) {
var data = new google.visualization.Datatable();
data.addColumn('string','Name');
data.addColumn('number','Quantity');
$.each(result, function(i, obj) {
data.addRow([ obj.name, parseInt(obj.quantity) ]);
});
var piechart_options = {
title : 'Pie Chart: How Much Products Sold By Last Night',
width : 400,
height : 300
}
var piechart = new google.visualization.PieChart(document
.getElementById('piechart_div'));
piechart.draw(data, piechart_options)
var barchart_options = {
title : 'Bar Chart: How Much Products Sold By Last Night',
width : 400,
height : 300,
legend : 'none'
}
var barchart = new google.visualization.BarChart(document
.getElementById('barchart_div'));
barchart.draw(data, barchart_options)
}
Related
I would like to display two lines in a Chart.js line chart. The required data from the database I have a JSON file with 2 objects.
Now I want to display them in the line chart. If I only want to display one data set it is no problem. When displaying two lines at the same time I have no idea what to do. I tried to call the objects and then output them, but the output is always undefined.
What am I doing wrong here?
Error:
Cannot read property 'current_week' of undefined
JSON Output:
{"current":[{"current_week":23},{"current_week":636},{"current_week":237}],"last":[{"last_week":235},{"last_week":74},{"last_week":737},{"last_week":767},{"last_week":546},{"last_week":73},{"last_week":453}]}
JS Chart.js Code:
$(document).ready(function() {
$.ajax({
url : "http://localhost/r6team-new/admin/includes/stats/website-weekly-stats.php",
type : "GET",
success : function(data) {
console.log(data);
var current_week = [];
var last_week = [];
for(var i in data) {
current_week.push(data.current[i].current_week);
last_week.push(data.last[i].last_week);
}
console.log(current_week);
console.log(last_week);
var visitorsChart = {
labels: ['MO', 'DI', 'MI', 'DO', 'FR', 'SA', 'SO'],
datasets: [{
type : 'line',
data : current_week,
backgroundColor : 'transparent',
borderColor : '#007bff',
pointBorderColor : '#007bff',
pointBackgroundColor: '#007bff',
fill : false
},
{
type : 'line',
data : last_week,
backgroundColor : 'tansparent',
borderColor : '#ced4da',
pointBorderColor : '#ced4da',
pointBackgroundColor: '#ced4da',
fill : false
}]
};
var ctx = $("#visitors-chart");
var LineGraph = new Chart(ctx, {
data: visitorsChart,
});
},
});
});
your loop is incorrect
var current_week = [];
var last_week = [];
for(var i in data["current_week"]) {
current_week.push(i["current_week"]);
}
for(var i in data["last_week"]) {
last_week.push(i["last_week"]);
}
or make it more easier
$(document).ready(function() {
$.ajax({
url : "http://localhost/r6team-new/admin/includes/stats/website-weekly-stats.php",
type : "GET",
success : function(data) {
var visitorsChart = {
labels: ['MO', 'DI', 'MI', 'DO', 'FR', 'SA', 'SO'],
datasets: [{
...
//current_week
data: data["current"].map(d => d["current_week"])
},
{
...
//last_week
data: data["last"].map(d => d["last_week"])
}]
};
var ctx = $("#visitors-chart");
var LineGraph = new Chart(ctx, {
data: visitorsChart
});
},
});
});
I am not a JavaScript expert and I am trying to put a simple pie chart together using the data from a csv file. The sample code for the pie chart with its input data looks like below and it works perfectly.
var pie = new d3pie("pie", {
header: {
title: {
text: "A Very Simple Pie",
fontSize: 30
}
},
data: {
content: [
{ label: "JavaScript", value: 264131 },
{ label: "Ruby", value: 218812 },
{ label: "Java", value: 157618}
]
}
});
but when I try to use the data from the csv file. It says no data is provided. I obviously try to pass the dynamic data to the data.content but it seems like I am not doing it correctly. Below is my code:
var input_data = []
d3.csv("data.csv", function (data) {
input_data.push({
label: data["First"],
value: +data["Age"]
});
});
console.log(input_data); // This shows [{label: "james", value:30},{"John",value:22}]
var pie = new d3pie("pie", {
header: {
title: {
text: "Simple Pie",
fontSize: 30
}
},
data: {
content: input_data
}
});
Any idea what I am doing wrong here?
As noted in my comment, your problem is because d3.csv acts asynchronously, and input_data isn't populated when d3pie tries to create your chart.
There is something highly suspicious going on with input_data in the other examples -- it should be called for every item in data, but seems only to be called once. Rather than using input_data to collate intermediate results, it's much easier to use javascript's map function to transform your csv data into the format you want:
d3.csv("data.csv", function (data) {
var pie = new d3pie("pie", {
header: {
title: {
text: "Simple Pie",
fontSize: 30
}
},
data: {
content: data.map( function(d){
return { label: d['First'], value: +d['Age'] }
})
}
});
});
map iterates over an array and produces an array as output, so it's much cleaner and easier than creating extra arrays on to which you push data, etc.
You probably want to put your d3pie code inside your callback function because you want to call it after the data returns (see this example):
var input_data = []
d3.csv("data.csv", function (data) {
input_data.push({
label: data["First"],
value: +data["Age"]
});
console.log(input_data); // This shows [{label: "james", value:30},{"John",value:22}]
var pie = new d3pie("pie", {
header: {
title: {
text: "Simple Pie",
fontSize: 30
}
},
data: {
content: input_data
}
});
});
const promise = d3.csv("data.csv", function (data) {
input_data.push({
'label': data["First"],
'value': +data["Age"]
});
});
promise.then(function(){
var pie = new d3pie("pieChart", {
header: {
title: {
text: "Simple Pie",
fontSize: 30
}
},
data: {
content: input_data
}
});
});
been trying to select data from data.sparkfun based on when its posted. I want to display weather data from the currenttime and a day back.
The stream is at: LINK
I am no coder, just hacking my way through here.
One json line is like this:
[{
"humidity": "37.8919",
"hectopascals": "1017.7725",
"rainin": "0.0000",
"tempc": "21.3162",
"winddir": "-1",
"windspeedkmh": "0.0000",
"windgustkmh_10m": "0.0000",
"timestamp": "2017-02-25T15:11:08.581Z"
}]
The code I use is at: https://www.hanscees.com/photon/charts-data-sparkfun.html
function drawChart2() {
var public_key = 'yA0EjKV3owhKNx1NlN3w';
// JSONP request
var jsonData = $.ajax({
url: 'https://data.sparkfun.com/output/' + public_key + '.json',
//data: {page: 1}, see http://phant.io/docs/output/http/
// https://forum.sparkfun.com/viewtopic.php?f=44&t=40621
data: {
'gt': {
'timestamp': 'now - 2d'
}
},
dataType: 'jsonp',
}).done(function(results) {
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Time');
data.addColumn('number', 'TempC');
data.addColumn('number', 'Humidity');
$.each(results, function(i, row) {
data.addRow([
(new Date(row.timestamp)),
parseFloat(row.tempc),
parseFloat(row.humidity)
]);
}); // each row
// see https://google-developers.appspot.com/chart/interactive/docs/gallery/linechart#dual-y-charts
var materialOptions = {
chart: {
title: 'TempC, Humidity outside'
},
width: 550,
height: 500,
series: {
// Gives each series an axis name that matches the Y-axis below.
0: {
axis: 'TempC'
},
1: {
axis: 'Humid'
}
},
axes: {
// Adds labels to each axis; they don't have to match the axis names.
y: {
Pressure: {
label: 'TempC (Celsius)'
},
Humid: {
label: 'Humidity'
}
}
}
};
var materialChart = new google.charts.Line(ChartDivTemp);
materialChart.draw(data, materialOptions);
}); // results
} // jsondata
but the diagrams are either displaying all data in the json file (which makes it extremely slow), or when I use:
data: {page: 1},
it shows about 4 hours of data.
How can help to format the query correctly? This line:
data: {
'gt': {
'timestamp': 'now - 2d'
}
}
I did a post request thru Postman and it worked:
https://data.sparkfun.com/output/yA0EjKV3owhKNx1NlN3w.json?lt[timestamp]=now%20-2day
data: {
'lt': {
'timestamp': 'now - 2day'
}
}
So you code should work by adding 2day and changing gt to lt
This code does what I wanted:
// JSONP request
var jsonData = $.ajax({
url: 'https://data.sparkfun.com/output/' + public_key + '.json',
//data: {page: 1}, see http://phant.io/docs/output/http/
// https://forum.sparkfun.com/viewtopic.php?f=44&t=40621
data: {'gt': {'timestamp': 'now - 2day'}},
dataType: 'jsonp',
}).done(function (results) {
var e = $.ajax({
type: "POST",
url: "<?php echo $template->get_template_dir('ajax',DIR_WS_TEMPLATES, $current_page_base,'ajax'); ?>/survey_save.php",
data: str
}).done(function(data) {
alert("Survey has been saved."+data);
$('#form').hide();
$('#results').show();
// data array for google chart
var e = [["Element", "Density", { role: "style" } ],["Copper", 8.94, "#b87333"],["Silver", 10.49, "silver"],["Gold", 19.30, "gold"],["Platinum", 21.45, "color: #e5e4e2"]];
return e;
});
google.charts.load("current", {packages:['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable(e);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{ calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation" },
2]);
var options = {
title: "Density of Precious Metals, in g/cm^3",
width: 600,
height: 400,
bar: {groupWidth: "95%"},
legend: { position: "none" },
};
var chart = new google.visualization.ColumnChart(document.getElementById("columnchart_values"));
chart.draw(view, options);
}
}
So the code above will return the data array as JSON. I need to either return it as an array or convert the JSON to an array format. How could I do that? When trying to call the
Explanation:
Pass AJAX request and get response data in JSON using mysql query. Feed response data to chart function.
In short, you need to get array values -> convert into JSON and give those values to google chart irrespective whether you need mysql or not. Modify code according to your requirement.
Client side main php
<script>
drawLineChart('<?php echo strtolower($chartType); ?>');
</script>
Client side function php
function drawLineChart(chartType, chartTitle) {
google.charts.setOnLoadCallback(lineChartData);
function lineChartData() {
var lineChartJsonData = $.ajax({
type: 'GET',
url: "<?php echo $server_script_path; ?>",
data: { id1: chartType, id2: "Chart" },
dataType:"json",
async: false,
beforeSend: function() {
},
success: function(data) {
},
}).responseText;
var options;
options = {
title: chartTitle,
width: '390',
height: '300',
vAxis: {title: '<title>'},
};
var data = new google.visualization.arrayToDataTable(($.parseJSON(lineChartJsonData)));
var chart = new google.visualization.LineChart(document.getElementById(chartType));
chart.draw(data, options);
}
}
Server side php file
if ($_GET['id1'] != "" && $_GET['id2'] == "Chart") {
// Chart type
$chartType = explode('-', $_GET['id1'])[1];
$sql = "<mysql query>";
$result = mysqli_query($conn, $sql);
$table = array();
$rows = array();
$rows[] = array('<column1>', '<column2>');
while($row = mysqli_fetch_array($result)) {
$rows[] = array('<rows>', '<rows>');
}
$table = $rows;
echo json_encode($table);
}
Live chart (my array data)
I've been looking through tons of examples but I can't seem to get my code to pull out the data. The chart is blank.
I have a php file that gives the following: (date, value1, value2)
[
["2013-09-15 08:44:37",19.8,8.19],
["2013-09-15 08:47:37",18.4,7.81],
["2013-09-15 08:50:37",18.3,7.78],
["2013-09-15 08:53:37",18.1,7.77]
]
I then have the following code:
<!DOCTYPE html>
<head>
<script src="js/jquery-1.10.2.min.js"></script>
<script src="js/highcharts.js" type="text/javascript"></script>
<script>
var chart;
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'line',
},
title: {
},
xAxis: {
type: 'datetime'
},
yAxis: {
},
series: [{
name: 'val1',
data: []
}, {
name: 'val2',
data: []
}]
};
$.getJSON('data_day.php', function(json) {
val1 = [];
val2 = [];
$.each(json, function(key,value) {
val1.push([value.time, value.val1]);
val2.push([value.time, value.val2]);
});
options.series[0].data = val1;
options.series[1].data = val2;
chart = new Highcharts.Chart(options);
});
});
</script>
</head>
<html>
I'm trying to use firebug to see where I've gone wrong. If I put
console.log(key,value)
under the $.each I can see the data:
0 ["2013-09-15 08:50:37", 18.3, 7.78]
1 ["2013-09-15 08:53:37", 18.1, 7.77]
2 ["2013-09-15 08:56:37", 18.2, 7.8]
Is there a problem with the
val1.push([value.time, value.val1]);
or
options.series[0].data = val1;
Update: Changed it to this and its now working.
val1.push([value[0], value[1]]);
val2.push([value[0], value[2]]);
As per Pal's comment - changed it to this:
val1.push([value[0], value[1]]);
val2.push([value[0], value[2]]);