'undefined is not a function' with google charts when using JSON - javascript

I have some JSON data and wanted to try out google charts. I used examples from the documentation from here and here
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API
google.load("visualization", "1", {packages:["corechart"]});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "get-stats.php",
dataType:"json",
async: false
}).responseText;
var options = {
title: 'Stats'
};
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!--Div that will hold the chart-->
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
When chart.draw() gets called, an error "undefined is not a function" appears on the site.
My JSON file gets loaded like this (get-stats.php)
<?php
$string = file_get_contents("stats.json");
echo $string;
?>
The JSON is formatted like that:
{
"cols": [
{
"id": "date",
"label": "Date",
"type": "datetime"
},
{
"id": "cntall",
"label": "Total",
"type": "number"
},
{
"id": "cntpers",
"label": "Pers",
"type": "number"
}
],
"rows": [
{
"c": [
{
"v": "new Date(2013, 11, 17, 9, 54, 0)"
},
{
"v": 320
},
{
"v": 123
}
]
},
{
"c": [
{
"v": "new Date(2013, 11, 17, 11, 4, 0)"
},
{
"v": 300
},
{
"v": 67
}
]
}
]
}
I suspect it has something to do with the JSON. All the code is from the google examples.

var data = new google.visualization.DataTable($jsonData);
Try this instead
$jsondata => json_encode($jsonData);
and put that with in php tag

Related

How to import Elasticsearch data(JSON) into Google Charts?

I try to use Elasticsearch data to create a table with Google Charts. I followed this solution: Populate Google Chart with Search Data from Elasticsearch
But I cannot see any data or graph displayed. I think it is because I don't transfer data correctly. Could anyone tell me the problem of the following code?
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
</script>
<script type="text/javascript">
google.load('visualization', {'packages':['table']});
google.setOnLoadCallback(drawTable);
function drawTable() {
var json;
$.ajax({
url: 'http://localhost:9200/people/man/_search',
type: 'POST',
data :
JSON.stringify(
{
"query" : { "match_all" : {} }
}),
dataType : 'json',
async: false,
success: function(data){
json = data;
}
})
var jdata = {};
jdata.cols = [
{
"id": "",
"label": "name",
"type": "string"
},
{
"id": "",
"label": "country",
"type":"string"
}
];
jdata.rows = [
{
"c": [
{
"v": json.hits.hits[0]._source.name
},
{
"v": json.hits.hits[0]._source.country
}
]
}
];
var data = new google.visualization.DataTable(jdata);
var table = new google.visualization.Table(document.getElementById('table_div'));
table.draw(data, {showRowNumber: true, width: '100%', height: '100%'});
}
</script>
</head>
<body>
<div id="table_div"> </div>
</body>
</html>
I find three problems of showing nothing in this code. No big error but good details to notice.
add header "Content-Type", "application/json". I used "xmlhttp.setRequestHeader("Content-Type", "application/json");"
'json' is defined in a function. If using json outside the function, it gives blank file back.(small error, but quite annoying if you don't notice this)
don't forget to transfer string to json with "var json = JSON.parse(json);"

Flot refuses to display data, but parses JSON labels fine

I want to show a line chart with points being added dynamically to multiple series (i.e. show progress). y axis: shows a float with one number after the decimal point and on the x axi: time, ideally formatted to show hour:minute:second. This is live data obtained with Ajax, returned formatted as JSON.
The data returned:
[
{
"label": "s#2 ch#1 (ch un)", "data": [1421941072,24.8]
}
,
{
"label": "s#2 ch#2 (2_ch2)", "data": [1421941072,23.9]
}
,
{
"label": "s#2 ch#3 (N/A)", "data": [1421941072,23.9]
}
]
The Javascript is displaying one big point in the middle of the chart and the legends correctly, nothing else.
No JavaScript error. Valid JSON.
It's maddening.
The complete code:
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery-ui.js"></script>
<script type="text/javascript" src="js/jquery.validity.js"></script>
<link href="./flotexamples.css" rel="stylesheet" type="text/css">
<script language="javascript" type="text/javascript" src="js/jquery.flot.js"></script>
<script language="javascript" type="text/javascript" src="js/jquery.flot.time.js"></script>
<script type="text/javascript">
function fetchData()
{
$.ajax({
url: "/graphlist.php",
type: "GET",
dataType: "json",
success: onDataReceived
});
function onDataReceived(series)
{
data = series;
var options =
{
series:
{
lines:
{
show: true,
},
points: {
show: true
}
},
xaxis:
{
mode: "time"
},
yaxis:
{
tickDecimals: 1
}
};
$.plot("#placeholder", data, options);
}
}
// every 5 seconds
var interval = 5000;
var tid = setInterval(fetchData, interval);
</script>
Any help greatly appreciated!
TIA,
Bert
You're data isn't correctly formatted. If I'm interpreting your intention correctly, the data should probably be
[
{
"label": "s#2 ch#1 (ch un)", "data": [[1421941072,24.8]]
}
,
{
"label": "s#2 ch#2 (2_ch2)", "data": [[1421941072,23.9]]
}
,
{
"label": "s#2 ch#3 (N/A)", "data": [[1421941072,23.9]]
}
]
Note that the data property is an array of arrays.
Of course, with this construction each data series is just a single data point, but that's the only way I can interpret your question. I'm assuming that later updates will add more points to each series.
You might find this chapter on flot helpful.

JavaScript - Black Chart by xCharts

I've managed to get a basic xChart work. Although, It returns some black screen instead of the graph I want. I've included all requirements such as d3.js and all xCharts's JS. My code and ouput below :
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<figure style="width: 400px; height: 300px" id="myChart"></figure>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="js/d3.js"></script>
<script src="js/xcharts.css"></script>
<script src="js/xcharts.js"></script>
<script type="text/javascript">
var data = {
"xScale": "ordinal",
"yScale": "linear",
"type": "bar",
"main": [
{
"className": ".pizza",
"data": [
{
"x": "Pepperoni",
"y": 12
},
{
"x": "Cheese",
"y": 8
}
]
}
],
"comp": [
{
"className": ".pizza",
"type": "line-dotted",
"data": [
{
"x": "Pepperoni",
"y": 10
},
{
"x": "Cheese",
"y": 4
}
]
}
]
}
var myChart = new xChart('bar', data, '#myChart');
</script>
<?php
// put your code here
?>
</body>
</html>
Anybody has any ideas about this and how to fix it?
I think you have simply forgotten to reference the CSS library. Something like:
<link href="xcharts.css" rel="stylesheet">
pointing to where you have stashed the file might do the trick.

HIghcharts Map from GeoJSON Data Showing Up Too Small

I am attempting to implement a custom interactive map using the Highcharts Maps JavaScript library (http://www.highcharts.com/maps/). I managed to get the map to appear on screen, but it far to small to view properly.
I took GeoJSON data for a map of Haiti with administrative boundaries.
The map is here: http://haitidata.org/layers/cnigs.spatialdata:hti_boundaries_communes_adm2_cnigs_polygon
This is a direct link to a GeoJSON file of the map data:
http://haitidata.org/geoserver/wfs?srsName=EPSG%3A4326&typename=cnigs.spatialdata%3Ahti_boundaries_communes_adm2_cnigs_polygon&outputFormat=json&version=1.0.0&service=WFS&request=GetFeature
Here is my HTML file:
<!DOCTYPE html>
<html>
<head>
<title>Homepage</title>
<link rel="stylesheet" type='text/css' href="css/normalize.css" type="text/css">
<link rel="stylesheet" type='text/css' href="css/main.css" type="text/css">
<link rel="stylesheet" type='text/css' href="css/responsive.css" type="text/css">
<!-- start JavaScript includes -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.highcharts.com/maps/highmaps.js"></script>
<script src="http://code.highcharts.com/maps/modules/map.js"></script>
<script src="js/haiti.js"></script> }
<!-- end JavaScript includes -->
</head>
<body>
<div id="container">
</div>
<p>This is some text.</p>
</body>
</html>
This is the content of haiti.js, a JavaScript file with the code to initialize the map:
$(function () {
// Prepare random data
var data = [
{
"id_dept": 1,
"value": 5000
},
{
"id_dept": 2,
"value": 10000
},
{
"id_dept": 3,
"value": 15000
},
{
"id_dept": 4,
"value": 20000
},
{
"id_dept": 5,
"value": 25000
},
{
"id_dept": 6,
"value": 30000
},
{
"id_dept": 7,
"value": 40000
},
{
"id_dept": 8,
"value": 5000
},
{
"id_dept": 9,
"value": 60000
},
{
"id_dept": 10,
"value": 70000
},
];
$.getJSON('js/haiti.json', function (geojson) {
// Initiate the chart
$('#container').highcharts('Map', {
title : {
text : 'GeoJSON in Highmaps'
},
mapNavigation: {
enabled: true,
enableDoubleClickZoom: true,
buttonOptions: {
verticalAlign: 'bottom'
}
},
colorAxis: {
},
series : [{
data : data,
mapData: geojson,
joinBy: ['id_com', 'id_dept'],
name: 'Random data',
dataLabels: {
enabled: true,
format: '{point.properties.id_com}'
}
}]
});
});
});
I have placed the GeoJSON data of the map in a separate file titled haiti.json. See link at top of question.
What I am doing wrong? The map is being displayed far too small and I am not able to click and zoom in on it.
Here is a screenshot of what is displayed on my screen. The container for the map should be 500px by 500px, so the map is showing up much small at just a few pixels width and height.
https://www.dropbox.com/s/844030r2o395zea/Screenshot%202014-08-01%2023.15.50.png
You can use maps from javascript and then use data module to add data to your map, like in the example: http://jsfiddle.net/X85CS/3/
var mapData = Highcharts.geojson(Highcharts.maps['countries/ht/ht-all']);
var data = [{
"value": 1438,
"code": "OU"
}];

Use server-side json with Highchart

I've searched for a few hours and looked for tons of examples, but in the end noting has worked for me.
My problem: I want to use a server-side json for a Line-Highchart. In the examples, which I've found the json comes either from a database or in an already preformated json-file.
For my use case it looks like the following: I want to visualize the value "depending" on their timestamp.
sampleData.json
[{
"timestamp": "2014-05-22T02:15:00+02:00",
"value": 235.0
}, {
"timestamp": "2014-05-22T02:30:00+02:00",
"value": 234.0
}, {
"timestamp": "2014-05-22T02:45:00+02:00",
"value": 234.0
}, {
"timestamp": "2014-05-22T03:00:00+02:00",
"value": 234.0
}, {
"timestamp": "2014-05-22T03:15:00+02:00",
"value": 234.0
}, {
"timestamp": "2014-05-22T03:30:00+02:00",
"value": 234.0
}, {
"timestamp": "2014-05-22T03:45:00+02:00",
"value": 234.0
}, {
"timestamp": "2014-05-22T04:00:00+02:00",
"value": 234.0
}, {
"timestamp": "2014-05-22T04:15:00+02:00",
"value": 234.0
}, {
"timestamp": "2014-05-22T04:30:00+02:00",
"value": 235.0
}, {
"timestamp": "2014-05-22T04:45:00+02:00",
"value": 235.0
}, {
"timestamp": "2014-05-22T05:00:00+02:00",
"value": 235.0
}]
This json file is read by my getData.php
<?php
// It reads a json formatted text file and outputs it.
$json_o = file_get_contents("sampledata.json");
echo $json_o;
?>
The output looks exactly like the input, so exactly like the sampleData.json itself.
Now I use my highchart.html to create a Highchart.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo</title>
<script type='text/javascript' src='//code.jquery.com/jquery-1.9.1.js'></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/data.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<!-- Additional files for the Highslide popup effect -->
<script type="text/javascript" src="http://www.highcharts.com/media/com_demo/highslide-full.min.js"></script>
<script type="text/javascript" src="http://www.highcharts.com/media/com_demo/highslide.config.js" charset="utf-8"></script>
<link rel="stylesheet" type="text/css" href="http://www.highcharts.com/media/com_demo/highslide.css" />
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto">
</div><style type='text/css'></style>
<script type='text/javascript'>
$(function () {
$(document).ready(function () {
$(document).ready(function () {
function requestData() {
$.ajax({
url : 'getData.php',
datatype : 'json',
success : function (data) {
alert(data);
chart.series[0].setData(data[0]);
},
cache : false
});
}
var chart;
//Chart bits
chart = new Highcharts.Chart({
chart : {
renderTo : 'container',
type : 'line',
events : {
load : requestData
}
},
title: {
text: 'Line Chart'
},
xAxis: {
type: 'datetime',
minRange: 1 * 24 * 3600000 // one day
},
yAxis : {
title : {
text : 'Value'
}
},
legend: {
enabled: true
},
series : [{
name : 'Random data',
data : [0]
}
]
});
});
});
});
</script>
</head>
<body></body>
</html>
I've also put all of it in a JsFiddle (unfortunately with a "XMLHttpRequest cannot load"-Error) but maybe it is useful: http://jsfiddle.net/ft8hc/1/
Now we come to my actual questions:
Until now I get no data into my Chart. Although it is created, but there is no data loaded. The json itself is loaded - alert(data) shows me the sampleData.json.
Although I've looked through existing examples, I could not figured out, how to define the attributes, which should be used to draw the line and the axes. For me timestamp and value should be used.
Additionally I am not sure, if the json Format is the right one that can be used by Highchart. Is it okay like this or do I have to parse it differently?
Would be absolutely awesome if someone could help me. I've tried it for hours without success :-(
This is because you have no data specified in your chart definition.
See:
series : [{
name : 'Random data',
data : [0]
}]
Upon getting the JSON data, you must PUSH that data into this Series.data and generate the chart thereafter.
You can refer to this solution : https://stackoverflow.com/a/8169187/3660930
Your json should
- use values x/y instead of your custom names
- date should be timestamp (time in miliseconds) [number type]
- value should be number

Categories

Resources