How to show the json data in Pie chart HighChart? - asp.net-mvc-3

HI all i have a json data which looks like this
[ "Data":[
{"Id":"1 ","EmployeeName":Anil},
]
which i am geting from my controller action
public ActionResult Index()
{
var data = GetData();
return View();
}
public JsonResult GetData()
{
int Param1;
Param1 = 1;
var EmployeeDetails = db.EmployeeDetails.ToList<EmployeeDetail>().Select(e =>
new
{
id=e.EmployeId,
Name = e.EmployeeName
});
return Json(EmployeeDetails , JsonRequestBehavior.AllowGet);
}
now i want this json data to a pie chart..how can i do this

Here instead of calling your jsonresult method in action method do it using $.getJSON method
public ActionResult Index()
{
return View();
}
public JsonResult GetData()
{
int Param1;
Param1 = 1;
var EmployeeDetails = db.EmployeeDetails.ToList<EmployeeDetail>().Select(e =>
new
{
id=e.EmployeId,
Name = e.EmployeeName
});
return Json(EmployeeDetails , JsonRequestBehavior.AllowGet);
}
here u can call your method like this and bind it to your chart
<script type="text/javascript">
$(function () {
$.getJSON('<%= Url.Action("YourMethod","YourControllerName") %>', {}, function (data) {
var json = data;
var jsondata = [];
for (var i in json) {
// var serie = new Array(json[i].Projects, json[i].Bugs);
jsondata.push([json[i].EmployeId, json[i].EmployeeName]);
}
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'pie',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'Resource Reports of BugTracker'
},
plotOptions: {
pie: {
showInLegend: true,
animation: false,
allowPointSelect: true,
cursor: 'pointer'
}
},
legend: {
enabled: true
},
series: [{
type: 'pie',
data: jsondata
}]
});
});
});
</script>

Regardless of what type of data you have, creating a pie chart is fairly straightforward. See a working example here: http://livecoding.io/3437833
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
plotOptions: {
pie: {
animation: false,
allowPointSelect: true,
cursor: 'pointer'
}
},
series: [{
type: 'pie',
name: 'Browser share',
data: [
['Firefox', 45.0],
['IE', 26.8],
['Safari', 8.5],
['Opera', 6.2],
['Others', 0.7]
]
}]
});

Related

How to use values from an ajax request in google charts?

I am creating an array of objects using Ajax to use as values in a google line chart, however the values do not render even though I can view them through the console.
I have tried using ajax complete function to call the charts once the values are set but it still doesn't work, I suspect it's due to scoping but I don't know how to resolve it. here is my code
complete array
studentCount[
{
month:1,
count:5
},
{
month:2,
count:3
},
{
month:3,
count:9
},
{
month:4,
count:0
}
{
month:5,
count:4
}
etc...
]
code
$.ajax({
dataType: "json",
url: url,
success: function (data) {
for (var i = 0; i < data.length; i++) {
studentCount[data[i].month -1].count = data[i].count;
}
}
});
$( document ).ajaxComplete(function() {
google.charts.load('current', {
packages: ['line']
});
google.charts.setOnLoadCallback(drawLineColors);
console.log(JSON.stringify(studentCount[0].count)) //returns correct value
function drawLineColors() {
var data = google.visualization.arrayToDataTable([
['Month', '2015'],
['January', studentCount[0].count],
['Febuary', studentCount[1].count],
['March', studentCount[2].count],
['April', studentCount[3].count],
['May', studentCount[4].count],
['June', studentCount[5].count],
['July', studentCount[6].count],
['August', studentCount[7].count],
['Septembre', studentCount[8].count],
['October', studentCount[9].count],
['November', studentCount[10].count],
['December', studentCount[11].count]
]);
var options = {
hAxis: {
title: 'Month'
},
vAxis: {
title: 'Number of Students'
},
colors: ['#4285f4', '#db4437']
};
var chart = new google.charts.Line(document.getElementById('chart_div'));
chart.draw(data, google.charts.Line.convertOptions(options));
}
});
recommend loading google first, you can include the callback directly in the load statement
once loaded, then call ajax
see following working snippet, adjust as needed to get proper data,
and change error to success as the url isn't reachable from here...
google.charts.load('current', {
callback: function () {
var url = 'some url';
$.ajax({
dataType: 'json',
url: url,
error: function (data) { // <-- change 'error' to 'success' to run locally
//for (var i = 0; i < data.length; i++) {
//studentCount[data[i].month - 1].count = data[i].count;
//}
var studentCount = [
{
month:1,
count:5
},
{
month:2,
count:3
},
{
month:3,
count:9
},
{
month:4,
count:0
},
{
month:5,
count:4
}
];
var data = google.visualization.arrayToDataTable([
['Month', '2015'],
['January', studentCount[0].count],
['Febuary', studentCount[1].count],
['March', studentCount[2].count],
['April', studentCount[3].count],
['May', studentCount[4].count]
// etc...
]);
var options = {
hAxis: {
title: 'Month'
},
vAxis: {
title: 'Number of Students'
},
colors: ['#4285f4', '#db4437']
};
var chart = new google.charts.Line(document.getElementById('chart_div'));
chart.draw(data, google.charts.Line.convertOptions(options));
}
});
},
packages: ['line']
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
also, recommend using core chart instead of material,
several config options simply don't work with material charts
core chart, use package --> corechart
and chart --> google.visualization.LineChart
you can use config option theme: 'material' to get the core chart close to the look and feel of a material chart
see following working snippet...
google.charts.load('current', {
callback: function () {
var url = 'some url';
$.ajax({
dataType: 'json',
url: url,
error: function (data) { // <-- change 'error' to 'success' to run locally
//for (var i = 0; i < data.length; i++) {
//studentCount[data[i].month - 1].count = data[i].count;
//}
var studentCount = [
{
month:1,
count:5
},
{
month:2,
count:3
},
{
month:3,
count:9
},
{
month:4,
count:0
},
{
month:5,
count:4
}
];
var data = google.visualization.arrayToDataTable([
['Month', '2015'],
['January', studentCount[0].count],
['Febuary', studentCount[1].count],
['March', studentCount[2].count],
['April', studentCount[3].count],
['May', studentCount[4].count]
// etc...
]);
var options = {
hAxis: {
title: 'Month'
},
vAxis: {
title: 'Number of Students'
},
colors: ['#4285f4', '#db4437'],
theme: 'material'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
});
},
packages: ['corechart']
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Kendo treeview HierarchicalDataSource not showing child nodes

I have a kendo Treeview which is showing the parent nodes but the child nodes are not seen. Can anyone tell me where am i going wrong. I am new to this concept. I followed the below link but its not working.
http://demos.telerik.com/kendo-ui/treeview/remote-data-binding
function treeView() {
var treeM = new kendo.data.HierarchicalDataSource({
schema: {
data: function (response) {
console.log("response" + JSON.stringify(response));
var rdata = {};
if (response.d) {
rdata = JSON.parse(response.d);
}
else {
rdata = response;
}
return rdata; // ASMX services return JSON in the following format { "d": <result> }.
},
model: {
hasChildren: true,
id: "ID",
expanded: true,
fields: {
ID: { editable: false, nullable: false, type: "string" },
LINK: { editable: true, nullable: true, type: "string" },
},
},
},
transport: {
read: {
url: "/getParent",
contentType: "application/json; charset=utf-8",
type: "POST",
datatype: "json"
},
parameterMap: function (data, type) {
if ((type == "update") || (type == "create") || (type == "destroy")) {
console.log('parameterMap:');
return JSON.stringify({ "LinksJson": data });
console.log(JSON.stringify(data));
} else {
return data;
}
}
}
});
$("#treeview1").kendoTreeView({
dataSource: treeM,
dataValueField: "ID",
dataTextField: ["LINK","Name"]
});
}
$("#treeview").on("click", ".k-in", function (e) {
var tree = $("#treeview").data('kendoTreeView');
tree.toggle($(e.target).closest(".k-item"));
});
$(document).ready(function () {
treeView();
});
Service:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string getParent()
{
using (var context = new Data.Entities())
{
IQueryable<ERPv2.Data.Links> dataQuery = from x in context.Links
where x.ParentID == 68
select x;
var newQry = dataQuery.AsEnumerable().Select(c => new
{
ID = c.ID,
Name = c.Name,
Children = HasChildren(231)
});
JavaScriptSerializer JSON = new JavaScriptSerializer();
return JSON.Serialize(newQry);
}
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public bool HasChildren(int ID)
{
using (var context = new Data.Entities())
{
IQueryable<ERPv2.Data.Links> dataQuery = from x in contextLinks
where x.ParentID == ID
select x;
return dataQuery.AsEnumerable().Any();
}
}
Even when you try to view the child nodes, it will try to call getLinks and not the getreports.
From what i have seen , you should have only one method for getting parent and children. Can be an array inside each parent node.
Can you combine the data from GetReports method inside getlinks itsself and give it a shot.
You should try and get this working here with hardcoded values and then do configure with services.
http://docs.telerik.com/kendo-ui/api/javascript/ui/treeview#configuration-dataSource

some confusion about kendo grid databind

I have one kendo grid where i am calling databinding dynamically.
Below is the code:
<div id="example">
<div id="grid"></div>
<script>
$(document).ready(function () {
var _dataSource = new kendo.data.DataSource({
transport: {
read: {
type: "POST",
url: "/Dashboard/GetAttritionEmployeeDetailsWithColl",
dataType: "json",
contentType: "application/json"
},
parameterMap: function (options, operation) {
return JSON.stringify(options);
}
},
schema: {
data: "Data",
errors: "Errors",
total: "Total",
model: {
fields: {
Department: { type: "string" },
}
}
},
pageSize: 20,
serverPaging: true,
serverFiltering: true,
serverSorting: true
});
$("#grid").kendoGrid({
dataSource:_dataSource,
height: 550,
filterable: true,
sortable: true,
pageable: true,
columns: [{
field: "Department",
title: "Department"
}
]
});
});
</script>
</div>
and here is the function used in dashboard controller
public List<Entity.EmployeeHeadCountResponse> GetAttritionEmployeeDetailsWithColl(Entity.DashboardEmpRequest request)
{
try
{
employeeHeadCountResponseList = new List<Entity.EmployeeHeadCountResponse>();
DashboardServiceAgent client = new DashboardServiceAgent();
request.FlapName = "Attrition";
request.LoggedInStaffId = "33019";
request.RoleName = "Administrator";
client.GetDashboardEmpDetailsWithBytes(request, (s, e) =>
{
if (e.GetType() == typeof(Service.GetDashboardEmpDetailsWithBytesCompletedEventArgs))
{
Service.GetDashboardEmpDetailsWithBytesCompletedEventArgs err = (Service.GetDashboardEmpDetailsWithBytesCompletedEventArgs)e;
if (err.Error == null && err.Result != null)
{
List<Service.GenericCollection> GenColl = new List<Service.GenericCollection>();
byte[] compress = err.Result;
GenColl = PayloadHelper.CompressedBytesToObject(compress) as List<Service.GenericCollection>;
HierarchyCollection collection = new HierarchyCollection(GenColl);
ServiceResult = GenColl;
EmpCollection = collection;
var mylist = EmpCollection.ToList();
if (EmpCollection != null)
{
dict = new HierarchyCollection().FillForCategoryValues(GenColl);
Employee_Read(request2);
}
}
}
}
);
}
catch (System.Exception ex)
{
Common.InsertLogging(ex);
}
return employeeHeadCountResponseList;
}
so in this function it is getting return data from wcf services so this is asynchronous service first time it is providing null value and second time it is getting the value so whenever it is getting data i am calling Employee_Read function inside this function. but not able to display data in kendo grid.
Now my question is here do i have to call main function which is returning json??
Instead of using
public List<Entity.EmployeeHeadCountResponse> GetAttritionEmployeeDetailsWithColl(Entity.DashboardEmpRequest request)
use
public ActionResult GetAttritionEmployeeDetailsWithColl()
and Return Plain Json instead of kendoDataSourceResult as you're already converting it to kendo datasource in the JavaScript side You must use
return Json(employeeHeadCountResponseList)
this is more than enough.

HighChart Pie Dynamic JSON in Codeigniter

Any help for this? The problem is I cannot get the data in pie. Any ideas? I tried to echo it outside the pie graph view, and the data appears in JSON as [{"Terminal":"13"}]. The Hightchart needs the data as ["Sample", 2]? Any suggestion sir on how to convert it like that? Thanks.
Heres my code:
VIEW
$(document).ready(function () {
$(function () {
var chart;
// Build the chart
$('.widget-lower-left#widget').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'Availability'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage}%</b>',
percentageDecimals: 1
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true
}
},
series: [{
type: 'pie',
name: 'Availability',
data: []
}]
});
});
function requestData() {
$.ajax({
url: 'home',
datatype: "json",
success: function(data) {
alert(data);
console.log(data);
chart.series[0].setData(data);
},
cache: false
});
};
});
then in the MODEL
$results = $this->db->query("SELECT COUNT(get_jeeps_availability) as Terminal FROM get_jeeps WHERE get_jeeps_availability = 'Terminal'");
return $results->result_array();
in the CONTROLLER
public function index()
{
$data['pie'] = json_encode($this->get_model->dashboard_jeep_widget());
$this->load->view('home',$data);
}
In requestData() function, before setting data, preprocess 'data' that way:
var newData = [];
for( var i = 0, len = data.length; i < len; i++ ) {
var item = data[i];
for(var j in item){
newData.push([j,item[j]]);
}
}
chart.series[0].setData(newData);

keep the Ids of selected results of Kendo UI Autocomplete in a hidden input

I wrote this code to use kendo UI autocomplete. I need to show the title of the selected result in the textbox and keep the if in some hidden input, how can I get the id. it seems the select doesn't work.
$("[data-autocomplete]").each(function () {
var luurl = $(this).attr('data-lookupurl');
var thisElemt = $(this);
$(this).kendoAutoComplete({
minLength: 3,
separator: ", ",
dataTextField: "title",
select: function (e) {
var selectedOne = this.dataItem(e.item.Index());
console.log(kendo.stringify(selectedOne));
},
dataSource: new kendo.data.DataSource({
serverFiltering: true,
serverPaging: true,
pageSize: 20,
transport: {
read: luurl,
dataType: "json",
parameterMap: function (data) {
return { title: thisElemt.val() };
},
schema: {
model: {
id: "id",
fields: {
id: { type: "id" },
title: { type: "string" }
}
}
}
}
})
});
});
There is a typo error, you should use: e.item.index() instead of e.item.Index() (index is lowercase).
So the select function would be:
select : function (e) {
var selectedOne = this.dataItem(e.item.index());
console.log(kendo.stringify(selectedOne));
},
and easier way is :
var autocomplete = $("#autoCompleteId").data("kendoAutoComplete");
console.log(autocomplete.listView._dataItems[0]);
you can access to select data item in autocomplete.listView._dataItems[0] object
you can use script
<script>
$(document).ready(function () {
$("#categories").change(function () {
var url = '#Url.Content("~/")' + "Limitations/ThanaByDistrict_SelectedState";
var ddlsource = "#categories";
var ddltarget = "#target";
$.getJSON(url, { Sel_StateName: $(ddlsource).val() }, function (data) {
$(ddltarget).empty();
$(ddltarget).val(data);
});
});
});
</script>
in controller like
// Get selected combox value
public JsonResult ThanaByDistrict_SelectedState ( Guid Sel_StateName )
{
JsonResult result = new JsonResult ( );
objects temp=db . objects . Single ( m => m . ob_guid == Sel_StateName );
result . Data = temp.ob_code;
result . JsonRequestBehavior = JsonRequestBehavior . AllowGet;
return result;
}
For details you can see this LINK

Resources