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

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);"

Related

Vertical stacked bar chart using SharePoint List

I have to create a stacked bar chart using the SharePoint complex list data using REST, JavaScript. The main problem here is i am not getting proper data sets.
Let me clear my scenario here: Suppose i am having a SharePoint-2013 list with 6 columns. I need a bar char based on column-1(Project Type) on x-axis, stacked by column-2(Technology) via count of different technology on y-axis. I am having 7 project type & 15 technology & want to processed around 200 rows with combination of them.
Project Java Python SharePoint .Net
A 3 5 12 1
B 4 7 6 3
C 0 9 1 0
I open with any Chat.js whether it is chart.js/google chart.js/highlight chat.js The only thing i need data to be dynamic means whenever user add more values to project column should added to x-axis automatically.
I am very new to this. Can anyone please help me to get this. need code part also. Many thanks in advance.
The code example for your reference:
<div style="width:600px;height:400px;">
<canvas id="myChart" width="600" height="400"></canvas>
</div>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.min.js"></script>
<script type="text/javascript">
var colors = ["#009EA0", "#A7A9AC", "#D15F27", "#BAD80A", "#E0AA0F", "#754760", "#373535"];
var listName = "CL26"; //Data List Name
var xAxisName="Title";
var yAxisName=["Java","Python","SharePoint","DotNet"];
$(document).ready(function() {
var requestUri = _spPageContextInfo.webAbsoluteUrl +
"/_api/Web/Lists/getByTitle('"+listName+"')/items";
//execute AJAX request
$.ajax({
url: requestUri,
type: "GET",
headers: { "ACCEPT": "application/json;odata=verbose" },
success: function (data) {
var myLabels=[];
var myDataSets=[];
$.each(data.d.results, function(i, item) {
myLabels.push(item[xAxisName]);
});
for(var i=0;i<yAxisName.length;i++){
var myData=[];
$.each(data.d.results, function(j, item) {
myData.push(item[yAxisName[i]]);
});
myDataSets.push({
label:yAxisName[i],
backgroundColor:colors[i],
data:myData
});
}
buildBarChart(myLabels,myDataSets);
},
error: function () {
//alert("Failed to get details");
}
});
});
function buildBarChart(myLabels,myDataSets){
var barChartData = {
labels: myLabels,
datasets: myDataSets
};
var ctx = document.getElementById('myChart').getContext('2d');
var myBar = new Chart(ctx, {
type: 'bar',
data: barChartData,
options: {
title: {
display: true,
text: 'MyProject'
},
tooltips: {
mode: 'index',
intersect: false
},
responsive: true,
scales: {
xAxes: [{
stacked: true,
}],
yAxes: [{
stacked: true
}]
}
}
});
}
</script>

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.

fusioncharts - Update FusionCharts data without changing chart settings

Is there a way to set Fusionchart graph "data" property only. Because currently when you set the the data at a latter stage, you need to pass the full json object which has both "data" and "chart" properties.
Below is my sample code;
FusionCharts.ready(function () {
var ageGroupChart = new FusionCharts({
id: 'total-users',
type: 'pie2d',
renderAt: 'chart-container',
width: '450',
height: '300',
dataFormat: 'json',
"chart": {
"caption": "Sample Graph",
"enableSmartLabels": "0",
"showPercentValues": "1",
"showTooltip": "0",
"decimals": "1",
"theme": "ocean"
},
"data":null
});
ageGroupChart.setJSONUrl( "http://www.example.com/GetData.php" );
ageGroupChart.render();
});
As you can see I'm setting the data from a online source. I'd prefer if the online source does not need to send the "chart" property along with the data. So I can separate the UI look and feel from data-source.
Any Ideas?
I'm using the following function throught XLMhttpRequest calls:
function updateChart(data) {
var jsonData = {
"chart": {
// Some rendering options
"caption": caption,
"subcaption": ""
},
"data": data
};
// First time I initialize my chart
if (FusionCharts("myChartId") === undefined) {
var chart = new myChartId({
// Some rendering options
swfUrl: "Charts/MSLine.swf",
id: "myChartId",
width: "100%",
height: "280px",
dataFormat: 'json'
});
chart.setJSONData(jsonData);
chart.render("myContainerId");
} else
// Then I just update
FusionCharts("myChartId").setJSONData(jsonData);
}
I call the updateChart function into my success callback:
success: function(data, request) {
try {
var d = JSON.parse(data);
updateChart(d.chart);
// Other job...
var event = new CustomEvent("dataReceivedFromAjax", {"detail": d});
document.dispatchEvent(event);
} catch (e) {
window.console.warn("Wrong format JSON data received");
window.console.warn(data);
}
}
Of course you may adapt my code to your case (for instance I'm using JsonData rather than JsonUrl).

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

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

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