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).
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 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
}
});
};
Data binding using Dev express and jquery.
Need to get table stored in odata store to bind with chart using widget dxchart.
Error in console window :$(...).dxChart is not a function
var context = new DevExpress.data.ODataContext({
url: "DataService.svc/",
entities: {
SalesEngine_Report_Pipelines:{},
SalesEngine_Report_TopTGOs:{},
}
});
var chartOptions = {
dataSource: {
store: context.SalesEngine_Report_Pipelines
},
title: "Tempelate",
size: {
height: 420
},
series: {
argumentField: "GroupName",
valueField: "NumGroup",
name: "My oranges",
type: "bar",
}
};
$("#chart").dxChart(chartOptions);
I Used to Spring MVC. This is my Java Service
#Override
public ArrayList<SampleVO1> getAvgPetalBySpecies3() {
ArrayList<SampleVO1> irisList = new ArrayList<SampleVO1>();
try {
REXP result = rEngine.eval("(ming <- tapply(iris$Petal.Length, iris$Species, mean))");
REXP result1 = rEngine.eval("names(ming)");
SampleVO1 sample1 = new SampleVO1();
sample1.setName(result1.asStringArray());
sample1.setY(result.asDoubleArray());
irisList.add(sample1);
} catch (Exception e) {
logger.error(e.getMessage());
throw new RuntimeException(e);
}
return irisList;
}
Oh! This is my VO
private String[] name;
private double[] y;
And This is my Controller
#RequestMapping("/analytics/iris3")
public String getAvgPetalbySpecies3(Model model) {
ArrayList<SampleVO1> irisList = analyticsService.getAvgPetalBySpecies3();
Gson gson = new Gson();
String irisData = gson.toJson(irisList);
model.addAttribute("irisData2", irisData);
return "analytics/visual";
}
At Last, This my JSP
<script type="text/javascript">
$(function() {
Highcharts.chart('pie', {
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: ''
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true
},
showInLegend: true
}
},
series:
<%= request.getAttribute("irisData2") %>,
});
});
</script>
enter image description here
lol I saw White space...
and I checked my sourceCode!
series:
[{"name":["setosa","versicolor","virginica"],"y":[1.462,4.26,5.552]}],
I thought I receive not bad to iris data! but my highCharts didn't like that...
How I fixed My code...?
You currently have the following code to add values to your data.
SampleVO1 sample1 = new SampleVO1();
sample1.setName(result1.asStringArray());
sample1.setY(result.asDoubleArray());
irisList.add(sample1);
Where you set name = [] of strings, and Y = []ยด of Doubles.
This gives you [[name, name, name],[y,y,y]]
Instead you should either join or loop through the number of elements in your lists as follows:
for(int i = 1; i < result.length(); i = i + 1) {
SampleVO1 sample1 = new SampleVO1();
sample1.setName(result1[i].asStringArray());
sample1.setY(result[i].asDoubleArray());
irisList.add(sample1);
}
Which will give you a list like [[name, y], [name, y], [name, y]].
I am sure there is much better ways to add two arrays together in java though.
Regardless, in the end you should en up with a JSON formatted list such as:
[{name: 'setosa', y: 1.462}, {name: 'versicolor', y: 4.26}]
Highcharts Series takes a JSON Object. You need to convert <%= request.getAttribute("irisData2") %> to a json object as below.
var irisData2_string = '<%= request.getAttribute("irisData2") %>';
var obj = JSON.parse(irisData2_string);
Thanks EveryOne!
I write my full code for pie-chart in highCharts!
First, I show My ValueObject!
public class SampleVO1 {
private String name;
private double y;
public String getName() {
return name;
}
public void setName(String resultList1) {
this.name = resultList1;
}
public double getY() {
return y;
}
public void setY(double resultList) {
this.y = resultList;
}
}
Second, My service!
#Service
public class AnalyticsService implements IAnalyticsService {
private static final Logger logger =
LoggerFactory.getLogger(AnalyticsService.class);
#Autowired
Rengine rEngine;
...
#Override
public ArrayList<SampleVO1> getAvgPetalBySpecies3() {
ArrayList<SampleVO1> irisList = new ArrayList<SampleVO1>();
try {
REXP result = rEngine.eval("(ming <- tapply(iris$Petal.Length, iris$Species, mean))");
REXP result1 = rEngine.eval("names(ming)");
double resultList[] = result.asDoubleArray();
String resultList1[] = result1.asStringArray();
for(int i=0; i<resultList.length; i++) {
SampleVO1 sample1 = new SampleVO1();
sample1.setName(resultList1[i]);
sample1.setY(resultList[i]);
irisList.add(sample1);
}
} catch (Exception e) {
logger.error(e.getMessage());
throw new RuntimeException(e);
}
return irisList;
}
Third, my Controller~
#Controller
public class AnalyticsController {
#Autowired
IAnalyticsService analyticsService;
#Autowired
IUploadFileService uploadFileService;
...
#RequestMapping("/analytics/iris3")
public String getAvgPetalbySpecies3(Model model) {
ArrayList<SampleVO1> irisList =
analyticsService.getAvgPetalBySpecies3();
Gson gson = new Gson();
String irisData = gson.toJson(irisList);
model.addAttribute("irisData2", irisData);
return "analytics/visual";
}
At last, My visualizing jsp!
<script type="text/javascript">
$(function() {
Highcharts.chart('pie', {
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: 'pie is ApplePie'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true
},
showInLegend: true
}
},
series: [{name: 'Species',
colorByPoint : true,
data :<%= request.getAttribute("irisData2") %>
}]
});
});
</script>
I hope these codes help you editing your highCharts!
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;
}
}