I want to input JSON data that I have from Database to highchart. but the chart didn't show up but JSON data does.
In ajax I already separate the category and data, but it's not working. especially because i don't know how to debug this javascript code. when I open inspect the sources in browser but it show nothing. I hope someone can help me
my ViewModel
public class DataByYear
{
public int Total { get; set; }
public string year { get; set; }
}
this is my Provider
public List<DataByYear> GetDataByYear()
{
tesdbEntities entities = new tesdbEntities();
var data = entities.Database.SqlQuery<DataByYear>("exec DataByYear");
return data.ToList();
}
I use SP to get the data from database
My Controller
public ActionResult Index()
{
return View();
var penjualan = new PenjualanProvider();
var index = new List<DataByYear>();
index = penjualan.GetDataByYear();
return this.Json(index, JsonRequestBehavior.AllowGet);
}
and this is my JS
$(document).ready(function () {
$.ajax({
url: '#Url.Action("Index")',
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: 'json',
async: true,
success: function (dataChart) {
var Xaxis = [];
var dataseries = [];
for (i = 0; i < DataByYear.length; i++) {
var items = DataByYear[i];
var XcategoreisItem = items.year;
var seriesData = items.Total;
Xaxis.push(XcategoreisItem);
dataseries.push(seriesData);
getchart(Xaxis, dataseries);
}
}
})
});
function getchart(Xaxis, dataseries) {
$('#data').highcharts({
chart: {
type: 'line',
zoomType: 'xy',
panning: true,
panKey: 'shift'
},
title: {
text: 'Profit From 2018'
},
plotOptions: {
series: {
dataLabels: {
enabled: true,
format: '{y}%',
}
}
},
xAxis: {
categories: Xaxis
},
yAxis: {
title: {
text: 'Y axis text'
},
series: dataseries
}
});
};
Related
I have to create a dynamic chart in my view based off a value a user would enter into an input contained in a beginform in my view, however it has to be done asynchronously thus why I am using Ajax and Json, I send the user input to the controller fine and then using that input my code creates two Arrays one string array that would be used as my labels for my chart and the other an int array that is used as the data values for the chart.
My issue is that I only manage to send one of those array's mentioned above and can't send them both and I am not sure how this would be done, I read somewhere that I could send the arrays as a collection but I'm not sure if this is correct.
Code in controller (I have removed all the code not related to the question and simplified it for illustration purposes):
public ActionResult DoChart(string data)
{
string[] product = {"Bread", "Milk", "Eggs", "Butter"};
int[] quant = {10, 20, 30, 40};
return Json(product, JsonRequestBehavior.AllowGet);
}
Javascript code in my View:
<script>
$(() => {
$("form#chartForm").on("submit", (e) => {
e.preventDefault();
let obj = {
quantity: $("#quantity").val()
};
$.ajax({
url: "#Url.Action("DoChart")",
method: "GET",
data: {
data: JSON.stringify(obj)
},
success: (product, status) => {
alert(product);
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: product,
datasets: [{
label: '# of Votes',
data: [1,2,3,4,5,6,7,8],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}
});
});
});
</script>
So in my code above I am sending the product array and then setting the labels for my chart, but I want to send the quant array as well and set the data values for my chart.
PS: I am using Chart.Js to create my chart.
Any help would be much appreciated.
Initially, you need a holder for your result. For example, you can create a holder class like below
public class MapResult
{
public string[] Products { get; set; }
public int[] Quantity { get; set; }
}
Controller
You can set the values of MapResult class from your controller, It has 2 arrays, One for product and 1 for quantity.
public ActionResult DoChart(string data)
{
string[] product = { "Bread", "Milk", "Eggs", "Butter" };
int[] quant = { 10, 20, 30, 40 };
var mapResult = new MapResult()
{
Products = product,
Quantity = quant
};
return Json(mapResult, JsonRequestBehavior.AllowGet);
}
AJAX Success code
AJAX result contains two arrays. You can add those to your map.
success: (result, status) => {
alert(result.Products);
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: result.Products,
datasets: [{
label: '# of Votes',
data: result.Quantity,
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
I'm trying to load a csv and format it so it will display as a chart in highcharts, this is proving difficult because of the structure of the csv data.
Here is the csv: https://pastebin.com/Ynz7GJJh
Sample:
iso,type,year,affected
JAM,Earthquake,1907,90000
JAM,Storm,1912,94820
TON,Volcano,1946,2500
DZA,Earthquake,1954,129250
HTI,Storm,1954,250000
Here is my highcharts.ajax so far
var hsOptions = {
chart: {
type: 'column'
},
title: {
text: 'KEY NATURAL HAZARD STATISTICS'
},
subtitle: {
text: 'Number of People Affected'
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Units'
}
},
series: []
};
Highcharts.ajax({
url: '/pathto.csv',
dataType: 'text',
success: function(csv) {
var rows = csv.split(/\r\n|\n/);
var cell;
var series = [];
var seriesBuilder = {name: countryValue, data: []};
for (var i = 0; i < rows.length; i++) {
cell = rows[i].split(',');
if (cell[0] === countryValue){
seriesBuilder.data.push(cell);
}
}
console.log(seriesBuilder);
series.push(seriesBuilder);
hsOptions.series.push(series);
Highcharts.chart('hazard-stats', hsOptions);
},
error: function (e, t) {
console.error(e, t);
}
});
which does make this
But I need this to build a series per disaster type, then the years have to combine on their own axis... it should be able to render just like this:
UI looks like this
<div class="col-md-3">
<select id="kMultiSelect" data-placeholder="Select Traits..." />
</div>
Javascript
<script>
var dataSourceTraits = new kendo.data.DataSource({
transport: {
read: {
url: "api/Traits",
dataType: "json"
},
create: {
url: "api/Traits",
type: "POST",
dataType: "json",
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
},
schema: {
model: {
ID: "Trait",
fields: {
ID: { type: "number" },
UID: { type: "string" }
}
}
}
});
$("#kMultiSelect").kendoMultiSelect({
autoBind: true,
dataTextField: "UID",
dataValueField: "ID",
dataSource: dataSourceTraits
});
</script>
Model
public int ID { get; set; }
public virtual string UID { get; set; }
.....
Controller
// GET: api/Traits
[HttpGet]
public IEnumerable<Trait> GetTrait()
{
// var test = _context.Trait;
return _context.Trait;
}
I have 4 rows in my table and I get 4 rows in the kendoMultiSelect each row just has "undefined" for text.
Looks like this
thanks for the help
after more help, entity framework core, by default, returns json. this datasource works
var dataSourceTraits = new kendo.data.DataSource({
type: "json",
transport: {
read: {
url: "api/Traits"
}
},
schema: {
model: {
fields: {
id: { type: "number" },
name: { type: "string" }
}
}
}
});
I am trying to create dynamic listbox values but getting this error in console:
Uncaught TypeError: Cannot assign to read only property 'active' of [
Here's my code( pasting only the code for listbox ):
body: [
{
type: 'listbox',
name: 'type',
label: 'Panel Type',
value: type,
'values': get_author_list(),
tooltip: 'Select the type of panel you want'
},
]
.....
And I am calling this function to get dynamic list...
function get_author_list() {
var d = "[{text: 'Default', value: 'default'}]";
return d;
}
I am guessing that the values in listbox only takes static var and not dynamic. But I need to insert dynamic values in this list. Please can anyone help me find a workaround. Is there any possibility to insert via ajax?
Thanks, in advance!!
I needed something similar for .NET site. Even though is not great code I hope it can help someone.
tinymce.PluginManager.add('DocumentSelector', function (editor, url) {
// Add a button that opens a window
editor.addButton('DocumentSelector', {
text: 'Document',
icon: false,
title: "Document Selector",
onclick: function () {
var _documentList;
//load all documents
var _data = JSON.stringify({/* Some data */});
$.ajax({
type: "POST",
url: "/api/TinyMCE/GetDocuments",
data: _data,
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (data) {
_documentList = eval('(' + data + ')');
// Open window
editor.windowManager.open({
title: 'Document Selector',
body: [
{
type: 'listbox',
name: 'DocURL',
label: 'Documents',
values: _documentList
},
{
type: 'textbox'
, name: 'TextToDisplay'
, value: _text
, label: 'Text To Display'
},
{
type: 'textbox'
, name: 'TitleToDisplay'
, value: _title
, label: 'Title'
},
{
type: 'listbox',
name: 'TheTarget',
label: 'Target',
values: [{ text: 'None', value: "_self" }, { text: 'New Window', value: "_blank" }],
value: _target
}
],
onsubmit: function (e) {
// Insert content when the window form is submitted
}
});
},
error: function (xhr, status, error) {
alert("Error! " + xhr.status + "\n" + error);
}
});
}
});
});
And here it is some of the Behind code
public class TinyMCEController : ApiController
{
public class DocumentsInfo
{
// Some data
}
public class DocumentList
{
public string text { get; set; }
public string value { get; set; }
}
[HttpPost]
[ActionName("GetDocuments")]
public object GetDocuments(DocumentsInfo docInfo)
{
//Test data
List<DocumentList> _DocumentList = new List<DocumentList>();
_DocumentList.Add(new DocumentList {
text = "Document1.pdf",
value = "value1"
});
_DocumentList.Add(new DocumentList
{
text = "Document2.pdf",
value = "value2"
});
var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(_DocumentList);
return json;
}
}
I have a problem with inserting data into highchart I try to customize example from http://www.highcharts.com/stock/demo
But my chart doesn't show any information, I looked at the example data, and it is in the same format as my data:
Here is my code in c#:
[HttpPost]
public JsonResult GetData()
{
...
var view= new JavaScriptSerializer().Serialize(dictionary.dicValues.Select(x => new object[] {x.Key, x.Value}));
view= Regex.Replace(view, #"\""\\/Date\((-?\d+)\)\\/\""", "$1");
view= view.Replace(#"[", "").Replace(#"]", "");
return new JsonResult
{
Data = new
{
view
},
ContentType = null,
ContentEncoding = null,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
Here is my js code for creating highchart:
$(elem).highcharts('StockChart', {
rangeSelector: {
selected: 1
},
title: {
text: "title"
},
xAxis: {
type: 'datetime',
},
yAxis: {
type: 'double',
},
series: [{
name: 'AAPL',
data: data.view,
tooltip: {
valueDecimals: 2
}
}]
});
And here is my data which I pass to the view:
"1421751600000,4.9928500000000007,1421755200000,13.314966666666665,1421758800000,8.316766666666668,1421845200000,14.738,1421848800000,7.9762000000000013"
or if I didn't erase the parentheses:
"[[1421751600000,4.9928500000000007],[1421755200000,13.314966666666665],[1421758800000,8.316766666666668],[1421845200000,14.738],[1421848800000,7.9762000000000013]]"
If someone could help me, I will be very grateful!
You should be able to simply this to:
public JsonResult GetData()
{
return new JsonResult()
{
Data = dictionary.dicValues.Select(x => new object[] {x.Key, x.Value})
};
}
The defaults for JsonResult should give you the correct settings for ContentType and it should automatically use the default serializer to serialize your object to a correct JSON string (unless you need some custom serialization).