Google Linecharts json data source? - asp.net-mvc

I use google line chart but I cant success to assing source to chart.
script
<script type="text/javascript">
// Load the Visualization API and the piechart package.
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: '#Url.Action("AylikOkumalar", "Enerji")',
dataType: "json",
async: false
}).responseText;
var rows = new google.visualization.DataTable(jsonData);
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', 'T1');
data.addColumn('number', 'T2');
data.addColumn('number', 'T3');
data.addRows(rows);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.LineChart(document.getElementById('chart_div')).draw(data, { curveType: "function",
width: 700, height: 400,
vAxis: { maxValue: 10 }
}
);
}
</script>
action
public ActionResult AylikOkumalar()
{
IEnumerable<TblSayacOkumalari> sayac_okumalari = entity.TblSayacOkumalari;
var sonuc = sayac_okumalari.Select(x => new
{
okuma_tarihi = ((DateTime)x.okuma_tarihi).ToShortDateString(),
T1 = (int)x.toplam_kullanim_T1,
T2 = (int)x.toplam_kullanim_T2,
T3 = (int)x.toplam_kullanim_T3
});
return Json(sonuc, JsonRequestBehavior.AllowGet);
}
json output
and script error:
Argument given to addRows must be either a number or an array.
I use it first time. So I dont know what should I do. How can use charts with mvc 3. there is no example enough.
Thanks.

data.addRows(rows);
'rows' should be an array - something like :
data.addRows([
[new Date(1977,2,28)], 1, 2, 3],
[new Date(1977,2,28)], 1, 2, 3]
]);
or your jsonData could be instead the whole structure :
{
"cols": [
{"id": "", "label": "Date", "type": "date"},
{"id": "", "label": "T1", "type": "number"}
],
"rows": [
{"c":[{"v": "Apr 24th"}, {"v": 56000} ]},
{"c":[{"v": "May 3rd" }, {"v": 68000} ]}
]
}

Related

creating dynamic table with data from odata service in ui5

I'm a complete newb on sap ui5.
I'm trying to generating a table on my webpage generated in sap web ide.
The data for this table is a .json file accessed via odata service.
I've come this far:
oModel is generated:
function initModel() {
var sUrl = "/sap/opu/odata/sap/ZGWS_someService/CollectionSet?$format=json";
var oModel = new sap.ui.model.odata.ODataModel(sUrl, true);
sap.ui.getCore().setModel(oModel);
}
now I want to generate a table on my html site with the data in the .json file.
So I have to create columns based on the properties of the items and then filling the rows with the current data.
.json looks like this:
{
"d": {
"results": [
{
"property1": "123",
"property2": "346"
},
{
"property1": "123",
"property2": "555"
}
I have no solution for this yet - can you help me out?
greetz,
simon
I created the table in the controller and sorted the data via lodash.
Is that good practice?
var oTable = this.byId("table");
oTable.addColumn(new sap.ui.table.Column({
label: new sap.ui.commons.Label({
text: "Info1"
}),
sortProperty: "INTST",
template: new sap.ui.commons.TextView().bindProperty("text", "key")
}));
oTable.addColumn(new sap.ui.table.Column({
label: new sap.ui.commons.Label({
text: "Count"
}),
template: new sap.ui.commons.TextView().bindProperty("text", "value")
}));
$
.ajax({
url: '/.../ServiceSet',
jsonpCallback: 'getJSON',
contentType: "application/json",
dataType: 'json',
success: function(data, textStatus, jqXHR) {
var oModel = new sap.ui.model.json.JSONModel();
oModel.setData(data);
sap.ui.getCore().setModel(oModel);
//Create a model and bind the table rows to this model
//Get the forecastday array table from txt_forecast object
var aData = oModel.getProperty("/d/results");
var aData2 = _.countBy(_.map(aData, function(d) {
return d.VALUE;
}));
var aData3 = Object.keys(aData2).sort().map(key => ({
key,
value: aData2[key]
}));
oModel.setData({
modelData: aData3
});
oTable.setModel(oModel);
}
});
oTable.bindAggregation("rows", {
path: "/modelData"
});

Export data from jqxgrid

I want to export all data in my jqxgrid into json and send it to another page via AJAX.
My problem is when I click export button, the data in the grid and data before export was not the same. It change float number to Interger. Here is my code:
Javascript:
$('#export_bt').on('click', function(){
var row = $("#jqxgrid").jqxGrid('exportdata', 'json');
$('#debug').html(row);
console.log(row);
});
var tableDatas = [
{"timestamp":"06:00:00","A":99.49,"B":337.77,"C":155.98},
{"timestamp":"07:00:00","A":455.67,"B":474.1,"C":751.68},
{"timestamp":"08:00:00","A":1071.02,"B":598.14,"C":890.47}
];
var tableDatafields = [
{"name":"timestamp","type":"string"},
{"name":"A","type":"number"},
{"name":"B","type":"number"},
{"name":"C","type":"number"}
];
var tableColumns = [
{"text":"Times","datafield":"timestamp","editable":"false","align":"center","cellsalign":"center","width":150},
{"text":"A","datafield":"A","editable":"false","align":"center"},
{"text":"B","datafield":"B","editable":"false","align":"center"},
{"text":"C","datafield":"C","editable":"false","align":"center"}
];
function setTableData(table_data,table_column,table_datafields)
{
sourceTable.localdata = table_data;
sourceTable.datafields = table_datafields;
dataAdapterTable = new $.jqx.dataAdapter(sourceTable);
$("#jqxgrid").jqxGrid({columns:table_column});
$("#jqxgrid").jqxGrid('updatebounddata');
$('#jqxgrid').jqxGrid('sortby', 'timestamp', 'asc');
$("#jqxgrid").jqxGrid('autoresizecolumns');
for(var i=0;i<table_column.length;i++){
$('#jqxgrid').jqxGrid('setcolumnproperty',table_column[i].datafield,'cellsrenderer',cellsrenderer);
}
}
var cellsrenderer = function (row, columnfield, value, defaulthtml, columnproperties) {
if (value||value===0) {
return value;
}
else {
return '-';
}
};
var sourceTable ={ localdata: '', datatype: 'array'};
var dataAdapterTable = new $.jqx.dataAdapter(sourceTable);
dataAdapterTable.dataBind();
$("#jqxgrid").jqxGrid({
width: '500',
autoheight:true,
source: dataAdapterTable,
sortable: true,
columnsresize: false,
selectionmode: 'none',
columns: [{ text: '', datafield: 'timestamp', width:'100%' , editable: false, align:'center'}]
});
setTableData(tableDatas,tableColumns,tableDatafields);
Html:
<div id="jqxgrid"></div>
<button id="export_bt">Export</button>
<div id="debug"></div>
http://jsfiddle.net/jedipalm/jHE7k/1/
You can add the data type in your source object as below.
datafields: [{ "name": "timestamp", "type": "number" }]
And also I suggest you to apply cellsformat in your column definition.
{ text: 'timestamp', datafield: 'timestamp', cellsalign: 'right', cellsformat: 'd' }
The possible formats can be seen here.
Hope that helps
You can export data in very fast way just like it is id jqxGrid with
var rows = $("#jqxGrid").jqxGrid("getrows");
It will be json array.

jQuery UI Autocomplete With Json Not Showing Suggestions

I'm experiencing some troubles with an autocomplete component from jQueryUi. The list with autocomplete suggestions doesn't appear.
I've tested the following code (from jQuery UI) and, despite servlet is sending a JSON object and "data" variable is storying it, component is still not showing suggestions list.
Also I tried the component with a simple list as source (like here), and it worked fine.
Have you any idea on what would be happening?
<script>
$(function() {
var cache = {};
$( "#bear" ).autocomplete({
minLength: 2,
source: function( request, response ) {
var term = request.term;
if ( term in cache ) {
response( cache[ term ] );
return;
}
$.getJSON( "/animals/MaintainMamals?operation=14", request, function( data, status, xhr ) {
cache[ term ] = data;
response( data );
});
}
});
});
</script>
<form>
<div class="ui-widget">
<label for="bear">Bear name (type a piece of name): </label>
<input id="bear" name="bear" class="text ui-widget-content ui-corner-all"/>
</div>
</form>
Json object used in testing (I tried the stuff with a simple jSon built with just a String refering to "name" property, with the same [bad] results):
[
{
"id": 1234567,
"name": "Yogi Bear",
"activity": {
"handler": {
"interfaces": [
{}
],
"constructed": true,
"persistentClass": {},
"getIdentifierMethod": {
"clazz": {},
"slot": 2,
"name": "getCod",
"returnType": {},
"parameterTypes": [],
"exceptionTypes": [],
"modifiers": 1,
"root": {
"clazz": {},
"slot": 2,
"name": "getId",
"returnType": {},
"parameterTypes": [],
"exceptionTypes": [],
"modifiers": 1,
"override": false
},
"override": false
},
"setIdentifierMethod": {
"clazz": {},
"slot": 3,
"name": "setId",
"returnType": {},
"parameterTypes": [
{}
],
"exceptionTypes": [],
"modifiers": 1,
"root": {
"clazz": {},
"slot": 3,
"name": "setId",
"returnType": {},
"parameterTypes": [
{}
],
"exceptionTypes": [],
"modifiers": 1,
"override": false
},
"override": false
},
"overridesEquals": false,
"entityName": "com.zoo.Activity",
"id": 7105,
"initialized": false,
"readOnly": false,
"unwrap": false
}
}
}
]
The autocomplete widget expects each item in your array to have a label property, a value property, or both. Since your data does not have either, you can either:
Tweak your server-side data source to return items that meet that criteria, or
Transform the data from your server-side code to match the criteria after you make the request.
I can only provide an answer to #2 since I don't see your server-side code, so here's how you would do that:
$(function() {
var cache = {};
$( "#bear" ).autocomplete({
minLength: 2,
source: function( request, response ) {
var term = request.term;
if (term in cache) {
response(cache[ term ]);
return;
}
$.getJSON("/animals/MaintainMamals?operation=14", request, function (data, status, xhr) {
/* Add a `label` property to each item */
$.each(data, function (_, item) {
item.label = item.name;
});
cache[term] = data;
response(data);
});
}
});
});
Here's an example that fakes an AJAX request--other than that it should be similar to your situation.

Highcharts to populate data for pie chart using json object

hi my json object looks like this
[
{"name":"Tokyo","data":3.0},
{"name":"NewYork","data":2.0},
{"name":"Berlin","data":3.5},
{"name":"London","data":1.5}
]
How to populate the series points to make a pie chart using highcharts
Try this below code. This will parse all the values and create an array called dataArrayFinal .
var d = [{"name":"Tokyo","data":3.0},{"name":"NewYork","data":2.0}, {"name":"Berlin","data":3.5},{"name":"London","data":1.5}]
var name = Array();
var data = Array();
var dataArrayFinal = Array();
for(i=0;i<d.length;i++) {
name[i] = d[i].name;
data[i] = d[i].data;
}
for(j=0;j<name.length;j++) {
var temp = new Array(name[j],data[j]);
dataArrayFinal[j] = temp;
}
And your series stuff should look like below. i.e, you should pass the array dataArrayFinal like below.
series: [{
type: 'pie',
name: 'Browser share',
data: dataArrayFinal
}]
Actually the only difference between your data definition and the format that Highcharts requires, is that yours has a property called "data" where Highcharts expects "y". So you just need to loop over the data and set that property. See it live at http://jsfiddle.net/highcharts/uTyZk/.
// Original data
var data = [{
"name": "Tokyo",
"data": 3.0
}, {
"name": "NewYork",
"data": 2.0
}, {
"name": "Berlin",
"data": 3.5
}, {
"name": "London",
"data": 1.5
}];
// Highcharts requires the y option to be set
$.each(data, function (i, point) {
point.y = point.data;
});
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'pie'
},
series: [{
data: data
}]
});

Jquery Autocomplete

iam using jquery autocomplete in asp.net project. it's not working. do you have any idea. the code is given below.
<script type="text/javascript">
$(function () {
$('#clientabbrev').val("");
$("#clientstate").autocomplete({
source: "clientstates.aspx",
select: function (event, ui) {
$('#clientstateid').val(ui.item.clientid);
$('#clientstateabbrev').val(ui.item.clientabbrev);
}
});
$("#clientstate_abbrev").autocomplete({
source: "clientstatesabbrev.aspx",
minLength: 2
});
});
</script>
problem is states.aspx returning the data but it is not showing in the jquery autocomplete control.
Your server needs to return a JSON serialized array of objects with properties id, label, and value. E.g. :
[ { "id": "1", "label": "Mike Smith", "value": "Mike Smith" }, { "id": "2", "label": "Bruce Wayne", "value": "Bruce Wayne" }]
Can you confirm with firebug or Fiddler that your server is returning the correct response?
If you're having trouble serializing your data in C#, you can try using JavaScriptSerializer like this:
var result = from u in users
select new {
id = u.Id,
value = u.Name,
label = u.Name
};
JavaScriptSerialier serializer = new JavaScriptSerializer();
var json = serializer.Serialize(result);
// now return json in your response

Resources