Highcharts : using JSON data as label to xaxis - json

I want to give name to xaxis as the data coming from JSON which will change dynamically
following is the code but it not labeling xaxis with the values store in key[obj] :
xAxis: {
categories: function(){
var data;
var obj = data[$("#host").val()].stats_vol.result.sectoutput;
for(var key in obj){
data.push({
name: key[obj],
categories : key[obj]
})
};
return data;
},
Can anyone please help to make this code work ??

Use setCategories method to update dynamically:
chart.xAxis[0].setCategories(categories);
Update
Here is working fiddle

Related

Create HighCharts-Column type from JSON

I am trying to create a column type highchart using data from json in the following format:
[{"id":7,"dateV":"2015-11-16","count":10},{"id":6,"dateV":"2015-11-15","count":3},{"id":5,"dateV":"2015-11-14","count":15},{"id":4,"dateV":"2015-11-13","count":10},{"id":3,"dateV":"2015-11-12","count":6},{"id":2,"dateV":"2015-11-11","count":8},{"id":1,"dateV":"2015-11-10","count":5}]
X axis should show the date values and the Y axis should show the count. Somehow i am not able to transform this JSON in the format required.
Here is my code.
<script type="text/javascript">
$('#myButton').click(function() {
var options = {
chart: {
renderTo: 'chartContainerDiv',
type: 'column'
},
series: [{}]
};
var url = "callToControllerURL";
$.getJSON(url, function(data) {
console.log(JSON.stringify(data));
options.series[0].data = JSON.stringify(data);
var chart = new Highcharts.Chart(options);
});
});
</script>
console log shows the JSON in format specified above. I am guessing i have to form the x and y axis values from the options array. How do i do it?
You need to iterate over the json data and create category data and series by pushing values.
var jsonData = [{"id":7,"dateV":"2015-11-16","count":10},{"id":6,"dateV":"2015-11-15","count":3},{"id":5,"dateV":"2015-11-14","count":15},{"id":4,"dateV":"2015-11-13","count":10},{"id":3,"dateV":"2015-11-12","count":6},{"id":2,"dateV":"2015-11-11","count":8},{"id":1,"dateV":"2015-11-10","count":5}];
var categoryData= [];
var seriesData= [];
$.each(jsonData, function(i,item){
seriesData.push(jsonData[i].count);
categoryData.push(jsonData[i].dateV);
console.log("seriesData"+JSON.stringify(seriesData));
});
See Working demo with your json here

How to get multiple data series into Highcharts

The following code works:
var options1 = {
chart: {
renderTo: 'container1'
},
series: [{}]
};
$.getJSON('tokyo.jsn', function(data){
options1.series[0].data = data;
var chart = new Highcharts.Chart(options1);
});
I want to be able to add a number of data series, so I am trying to take the reference to ‘new Highcharts’ out of the getJSON, but I don't seem to get it right. This following code does not work:
$.getJSON('tokyo.jsn', function(data){
options1.series[0].data = data;
});
var chart = new Highcharts.Chart(options1);
I have also tried tackling it a different way but again the following code does not work:
var chart1 = new Highcharts.Chart({
chart: {
renderTo: 'container1'
},
series: [{}]
});
$.getJSON('tokyo.jsn', function(data){
chart1.series[0].data = data;
});
Can anyone point me in the correct direction. I need to be able to support multiple data series by doing a second getJSON call like the following:
$.getJSON('sydney.jsn', function(data){
options1.series[1].data = data;
});
The JSON code I'm using is as follows:
[ 7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6 ]
Thanks
$.getJSON is an asynchronous request. Once you receive the data, then you can pass it to Highcharts, thus you have to call that code from within the callback function of $.getJSON().
Try this, use a helper function to process your data and draw the chart, see drawChart() below:
var options1 = {
chart: {
renderTo: 'container1'
},
series: []
};
var drawChart = function(data, name) {
// 'series' is an array of objects with keys:
// - 'name' (string)
// - 'data' (array)
var newSeriesData = {
name: name,
data: data
};
// Add the new data to the series array
options1.series.push(newSeriesData);
// If you want to remove old series data, you can do that here too
// Render the chart
var chart = new Highcharts.Chart(options1);
};
$.getJSON('tokyo.jsn', function(data){
drawChart(data, 'Tokyo');
});
$.getJSON('sydney.jsn', function(data){
drawChart(data, 'Sydney');
});
See fiddle: http://jsfiddle.net/amyamy86/pUM7s/
You can use solution used by Highcharts in that example: http://www.highcharts.com/stock/demo/compare
Or first create empty chart, without any series, and then use addSeries() function in each callback, see: http://api.highcharts.com/highcharts#Chart.addSeries()

JSON parse issue in Titanium

I am working on simple task read the data from url which is in JSON format and display those fields in Table
i written code like as
var Win = Titanium.UI.currentWindow;
//SEARCH BAR
var xhr = Titanium.Network.createHTTPClient();
tableData=[];
Win.open();
xhr.onload = function() {
alert('res'+this.responseData);
var json = this.responseText;
var response = JSON.parse(json);
//-- Mail was sent
alert('respoinse length : '+response.result.length);
tableData=[];
for (i = 0; i < response.result.length; i++) {
sresult = response.result[i];
//alert('City'+ sresult.city);
var row = Ti.UI.createTableViewRow({
rowID: i,
color:'#222',
left:70, top:44,
width:360,
text:sresult.County
});
tableData.push(row);
}
table.setData(tableData);
};
var table = Titanium.UI.createTableView({
top:60,
data:tableData
});
Win.add(table);
//xhr.open('GET', 'https://www.clia.livestockid.ca/CLTS/public/division/CCIA/en/splash_logo.jpg');
xhr.open('GET', 'http://gomashup.com/json.php?fds=geo/usa/zipcode/city/STERLING');
xhr.send();
i run it on Titanium - the first alert showing the JSON data. after that its not getting alert of second one not sure ... why its not moving to next step... please help me on this is there any mistakes in code or else parsing issue.
Thanks
Devendar
The "JSON" returned by the url you gave (http://gomashup.com/json.php?fds=geo/usa/zipcode/city/STERLING) is invalid. (http://jsonlint.com is a useful resource for checking that sort of thing.) It starts with a ( and ends with a ), like this:
({
"result":[
{
"Longitude" : "-071.939375",
"Zipcode" : "01564",
"ZipClass" : "STANDARD",
"County" : "WORCESTER",
"City" : "STERLING",
"State" : "MA",
"Latitude" : "+42.366765"
}
]}
)
(I've omitted a lot from that.)
JSON documents start with either [ or {, and end with the corresponding ] or }.
The above would be valid without the ( at the beginning and ) at the end, so you could always remove them before parsing, but the real answer is to fix the feed.

Update chart data in Dojo

I have the below function which reads JSON data and puts it on a chart. I would like to automatically update the chart data every say 10 seconds.
I have looked at dojo/timing and chart.updateSeries and I believe the combination of the two would do the trick but I'm not sure how I can implement this. Any help would be greatly appreciated.
function(xhr, json, arrayUtil, number, Chart, theme) {
var def = xhr.get({
url: "cpuusage.json",
handleAs: "json"
});
def.then(function(res){
var chartData = [];
arrayUtil.forEach(res.chart, function(chart){
chartData[chart.x] = number.parse(chart.y);
});
//Draw chart
var chart = new Chart("chartNode2");
chart.setTheme(theme);
chart.addPlot("default", {
type: "Columns",
markers: true,
gap: 5
});
chart.addAxis("x");
chart.addAxis("y", { vertical: true, fixLower: "major", fixUpper: "major" });
chart.addSeries("Monthly Sales",chartData);
chart.render();
}, function(err){
console.error("Failed to load JSON data");
});
}
Try something like that:
var interval = setInterval(function(){
// let's get new data
xhr.get({
url: "cpuusage.json",
handleAs: "json"
}).then(function(res){
// data prep step - just like before
var chartData = [];
arrayUtil.forEach(res.chart, function(chart){
chartData[chart.x] = number.parse(chart.y);
});
// update chart (it was created before)
chart.updateSeries("Monthly Sales", chartData);
chart.render();
}, function(err){
console.error("Failed to load updated JSON data");
});
}, 10000); // 10s
...
// when we want to cancel updates
clearInterval(interval);
Sorry, I didn't use dojo/timing, I don't see much reason for it here, and prefer simple ways to do simple things.

How do I make an Ext.Panel show a DataView using a JsonStore and XTemplate?

This seems like it should be simple. Here is my data store declaration:
var dataStore = new Ext.data.JsonStore({
autoLoad : true,
url : '#mvclink(' json.getCostReportsJsonData ')#&layout_type=txt',
root : 'data',
id : 'dataStoreId',
fields : ['project', 'cost']
});
The url is actually generated by ColdFusion, which calls the query and converts it to Json format. I think everything works correctly here, because the Json object comes back as:
{"recordcount":1,"columnlist":"project,cost","data":[{"project":"ABC","cost":2250}]}
I have dummy data in there for now, so just one row is returned.
Next, I declare an Ext.Panel with a DataView in it:
var myPanel = new Ext.Panel({
layout : 'fit',
id : 'myPanel',
title : "My Panel",
monitorResize : true,
deferredRender : false,
items : new Ext.DataView({
store : dataStore,
tpl : costReportTemplate
}),
renderTo : Ext.getBody()
});
The template referenced is an XTemplate:
var costReportTemplate = new Ext.XTemplate(
'<tpl for=".">',
'<p><b>{project}</b>: {cost:this.format}</p>',
'</tpl>', {
format : function (v) {
var s = Ext.util.Format.usMoney(v);
return s.substring(0, s.indexOf('.'));
}
});
Upon rendering the page, I can see the panel, but it's completely empty, and I get no errors in Firebug. What am I doing wrong?
I figured it out! I hadn't used a dummy cost value with a decimal point, so the format function wasn't working properly. I wasn't getting any errors, though. I changed it to check if (s.indexOf('.') != -1) and everything is fine now.