Loading external json file in highchart - javascript

When loading external JSON file in HighCharts it shows nothing in the browser. I have following JSON data. I have included highchart.js and jquery.js in the head of my HTML code, but still I cannot get a bar chart in my browser. No error is shown in console when checking the console.
var json = [{
"key": "Apples",
"value": "4"
}, {
"key": "Pears",
"value": "7"
}, {
"key": "Bananas",
"value": "9"
}];
var processed_json = new Array();
$.map(json, function(obj, i) {
processed_json.push([obj.key, parseInt(obj.value)]);
});
$('#container').highcharts({
chart: {
type: 'column'
},
xAxis: {
type: "category"
},
series: [{
data: processed_json
}]
});

That is because the order of execution is different than we expect. ie The JSON loading section execution is happening before it get initialized.
You can put the JSON loading section code in one function and call that function after initialization function is completed(.success or .done in the HTML element's event).
I had one AJax function so I called this JSON loading function in the success of that AJAX call.
Code:
var json = [{
"key": "Apples",
"value": "4"
}, {
"key": "Pears",
"value": "7"
}, {
"key": "Bananas",
"value": "9"
}];
var processed_json = new Array();
$.map(json, function(obj, i) {
processed_json.push([obj.key, parseInt(obj.value)]);
});
if (processed_json.length != 0) {
loadJson();
}
function loadJson() {
$('#container').highcharts({
chart: {
type: 'column'
},
xAxis: {
type: "category"
},
series: [{
data: processed_json
}]
});
}

Related

Load json from text file

I have the following hard coded json,
var dataLocality = [
{ "label": "Arwen" },
{ "label": "Bilbo Baggins" },
{ "label": "Boromir" },
{ "label": "Frodo Baggins" },
{ "label": "Peregrin Pippin Took" },
{ "label": "Samwise Gamgee" }
];
Which I use to populate an autocomplete textbox with the following script,
$(function () {
$("#locality").autocomplete(
{
source: dataLocality
})
});
I now have a text file that is dynamically updated via my app named dataLocality.text which i'm able to load and view in an alert box with this code,
function codeAddress() {
jQuery.get('http://localhost/project/jSonDocs/dataWhat.txt', function (data) {
var dataLocality = data;
alert(dataLocality);
});
}
window.onload = codeAddress;
But I can't seem to work out how to get the data from var dataLocality to source: dataLocality
The data in my text doc looks like this,
[
{ "label": "Arwen" },
{ "label": "Bilbo Baggins" },
{ "label": "Boromir" },
{ "label": "Frodo Baggins" },
{ "label": "Peregrin Pippin Took" },
{ "label": "Samwise Gamgee" }
];
Assuming you're using the jQueryUI autocomplete method, you can provide the URL of the JSON to the source method and it will retrieve it for you automatically. Try this:
$("#locality").autocomplete({
source: 'http://localhost/project/jSonDocs/dataWhat.txt'
});
If you still prefer to retrieve the JSON manually (if you need to change the source after initialisation for example) then you can achieve it like this:
function codeAddress() {
jQuery.get('http://localhost/project/jSonDocs/dataWhat.txt', function (data) {
$('#locality').autocomplete('option', 'source', data);
});
}

How do I loop through this Json object (angularJS)?

I'm trying to loop through "tabs" in the Json object using AngularJS? How can I do it?
var model = {
"$id": "1",
"tabs": [{
"$id": "2",
"id": 2,
"name": "Output",
"layoutId": 1,
"order": 1,
"dashboardId": 1
}, {
"$id": "15",
"id": 3,
"name": "Yield",
"layoutId": 1,
"order": 2,
"dashboardId": 1
}, {
"$id": "24",
"id": 4,
"name": "Trend",
"layoutId": 1,
"order": 3,
"dashboardId": 1
}],
"id": 1,
"name": "Test",
"title": "Test",
"description": "Test Dashboard",
"createDate": "2015-06-08T00:00:00+01:00",
"ownerId": 1,
"enabled": true
};
When I try this, I get "undefined" in the console.
angular.forEach(model.tabs, function (tab) {
console.log(tab.name);
});
not sure what I'm doing wrong?
EDIT:
The data is coming from ASP.Net controller:
$http.get("/Dashboards/GetDashboardData").success(function (data) {
model = data;
angular.forEach(model.tabs, function (tab) {
console.log(tab.name);
});
}).error(function (data) {
console.log("error");
});
I expect that the model is not ready at the time you loop though it. Run the following code with your inspector open - the code you have is correct, but in your case fails because model isn't ready when you run the loop.
If you're loading data asyncronously you'll want to wait until the data is returned, either using a promise or a callback, and the loop through it.
var model = {
"tabs": [{
"name": "Output",
}, {
"name": "Yield",
}, {
"name": "Trend",
}],
};
angular.forEach(model.tabs, function (tab) {
console.log(tab.name);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
Ok I found the answer. It looks like my controller returns Json object as a string, so I have to switch it to object before I can use it as an object.
I have add this line before using model in the loop:
model = JSON.parse(data);
The whole solution with promise (not sure if I need it now):
DataService.getDashboardData().then(function (data) {
model = JSON.parse(data);
angular.forEach(model.tabs, function (tab) {
console.log(tab);
});
});
app.service("DataService", ["$http", "$q", function ($http, $q) {
return {
getDashboardData: function () {
var dfd = $q.defer();
$http.get('/Dashboards/GetDashboardData').success(function (result) {
dfd.resolve(result);
});
return dfd.promise;
}
};
}]);

JSon with HighCharts and ASP.NET

I'm new using highcharts and JSON.
My javascript code is this:
$(document).ready(function() {
var options = {
chart: {
renderTo: 'grafica',
type: 'spline'
},
series: [{}]
};
$.getJSON('ajax/gettipomov.aspx', function(data) {
options.series[0].data = data;
var chart = new Highcharts.Chart(options);
});
});
And the data returned by the server and received by JavaScript is this:
[{"tipoMov":"Ajuste negativo","valorTipoMov":5},{"tipoMov":"Ajuste positivo","valorTipoMov":5},{"tipoMov":"Compra","valorTipoMov":5}, {"tipoMov":"Transferencia","valorTipoMov":5},{"tipoMov":"Venta","valorTipoMov":5}]
The problem is that chart is not showing any data, the chart is blank: image
The JSON Encoding that I use is:
var encoder = new JavaScriptSerializer();
return encoder.Serialize(obj);
That's the format expected:
{ "name": "Ajuste negativo", "y": 5 },
{ "name": "Ajuste positivo", "y": 5 },
{ "name": "Compra", "y": 5},
{ "name": "Transferencia", "y": 5},
{ "name": "Venta", "y": 5}
tipoMov and valorTipoMov mean nothing to Highcharts, so change your Object to return the properties named accordingly.

JQXMenu Databind with JSON

I am developing an application where I need to fetch the menu items from a text file.
I am new to JQX.
But while displaying the records its showing nothing.
My Text File(LeftMenu.txt) as below:
[{
"text": "Menu1",
"id": "1",
"parentid": "-1"
},
{
"text": "Menu2",
"id": "2",
"parentid": "-1"
},
{
"text": "Menu3",
"id": "3",
"parentid": "-1"
}
]
==========================================================================
The code is here under
// prepare the data for Left Menu
var urlleftpanel = "../../Public/sampledata/leftmenu.txt";
var sourceleftmenu =
{
datatype: "json",
datafields: [
{ name: 'id' },
{ name: 'parentid' },
{ name: 'text' }
],
id: 'id',
url: urlleftpanel
};
// create data adapter.
var dataAdapter1 = new $.jqx.dataAdapter(sourceleftmenu);
// perform Data Binding.
dataAdapter1.dataBind();
var records = dataAdapter1.getRecordsHierarchy('id', 'parentid', 'items', [{ name: 'text', map: 'label' }]);
var records = da.records;
$('#jqxWidget').jqxMenu({ source: records , height: 53, theme: theme, width: '95px' });
=====================================================================================
Please Help its very urgent
Thanks in Advance
Try setting async: false in the source object.
var sourceleftmenu =
{
datatype: "json",
async: false,
datafields: [
{ name: 'id' },
{ name: 'parentid' },
{ name: 'text' }
],
id: 'id',
url: urlleftpanel
};

How to add response from AjaxRequest to a store or display it on a list

I had a sencha touch code which connects to a WebService using Ext.Ajax.request. On success function, I want the response to be displayed in a list or store it in a Store.
Please help me how to do that. Below is my code.
var View = function() {
Ext.getBody().mask('Loading...', 'x-mask-loading', false);
Ext.Ajax.request({
url: 'URL',
method: 'GET',
success: function(response, opts)
{
var obj = Ext.util.JSON.decode(response.responseText);
Ext.getCmp('content').update(response.responseText);
}
});
};
create a Ext.List with store attribute,
myStore = new Ext.data.Store({
model: Ext.regModel('', {
fields: [
{ name: 'id', type: 'int' },
{ name: 'name', type: 'string'},
{ name: 'age', type: 'string'}
]
})
});
myList = new Ext.List({
store: myStore,
itemTpl: '<div>{name}</div>' +'<div>{age}</div>'
});
Then fill the myStore store with results of Agax request. onsuccess event in ajax call should be as follows,
var jsonData = Ext.util.JSON.decode(response.responseText);
myStore.add(jsonData['myresultlist']);
myStore.sync();
Then make sure You are returning a valid json from the server side as follows,
{
"myresultlist": [
{
"id": "1",
"name": "anne",
"age": "21"
},
{
"id": "2",
"name": "jack",
"age": "26"
},
{
"id": "3",
"name": "Tom",
"age": "21"
}
],
"success": "true",
"info": "My Results List!"
}

Categories

Resources