Recently im working on c3 charts its actually working great
but i had a problem with dynamically get multiple data in DB
Multiple XY Lines chart
X had to be in string
I actually want multiple xy values and x values had to be string
After a long period i dont get any ideas
I tried json method in ajax
$.ajax({
type: "POST",
url: "../Home/timechart",
data: Getdata,
contentType: "application/json; chartset=utf-8",
dataType: "json",
success: function (response) {
successClass(response)
},
});
function successClass(jsondata) {
var data = {};
var mvalue = [];
var mdatetime = [];
var TagID = [];
jsondata.forEach(function (e) {
mvalue.push(e.mvalue);
mdatetime.push(e.mdatetime);
if (TagID != e.TagID) {
TagID.push(e.TagID);
}
})
//alert(objvalue)
// alert(objdate)
var chart = c3.generate({
bindto: '#chart',
data: {
columns: [
/* ['x'].concat(mdatetime),*/
[TagID].concat(mvalue)
]
},
axis: {
x: {
type: 'category',
categories: mdatetime,
tick: {
rotate: -25,
multiline: false
},
height: 130
}
},
legend: {
position: 'outer-center'
}
});
}
}
});
});
i can get a chart in single dynamic value but dont know how to get multiple y values and same x value in it
Related
I have Kendogrid grid that I get the data by JSON for the URL that I have and activate Selection mode as I found the kendo grid documentation, but I am trying to get the selected data from kendo grid, try some methods in javascript but not yet I have been able to do it. If someone can help me?
$(document).ready(function () {
$("#grid").kendoGrid({
toolbar: ["excel"],
excel: {
fileName: "user.xlsx",
filterable: true
},
dataSource: {
transport: {
read: {
url: `/user`
}
},
schema: {
data: function (response) {
return response.permisos;
},
model: {
fields: {
id: { type: "number" },
nombre: { type: "string" },
descripcion: { type: "string" }
}
}
},
pageSize: 20
},
height: 550,
scrollable: false,
sortable: true,
filterable: true,
pageable: true,
persistSelection: true,
change: onChange,
columns: [
{ selectable: true, width: "50px" },
{ field: "id", title: "Id" },
{ field: "nombre", title: "Nombre" },
{ field: "descripcion", title: "DescripciĆ³n" }
]
});
$("#grid").data("kendoGrid").wrapper.find(".k-grid-header-wrap").off("scroll.kendoGrid");
});
I found two solutions, the first one is activating the change: onchange, one can obtain the selected checkboxes, each time one selects. What I'm doing is going through the checkboxes and saving them in a list
function onchange(e) {
var permiso = [];
var numero = 0;
var rows = e.sender.select();
rows.each(function (e) {
var grid = $("#grid").data("kendogrid");
var dataitem = grid.dataitem(this);
var recibir = dataitem;
console.log(dataitem);
console.log("dato recibido" + recibir.id);
permiso.push(recibir.id);
})
console.log("largo: " + permiso.length);
for (var i = 0; i < permiso.length; i++) {
console.log("array: " + permiso[i]);
}
And the other way is that you added a button that activates the event to go through the grid to get the checkbox, which is the best for me
$("#saveChanges").kendoButton({
click: function (e) {
var permiso = [];
var entityGrid = $("#grid").data("kendoGrid");
var rows = entityGrid.select();
rows.each(function (index, row) {
var selectedItem = entityGrid.dataItem(row);
var recibir = selectedItem;
console.log(selectedItem);
console.log("Dato recibido rows.each" + recibir.id);
permiso.push(recibir.id);
});
for (var i = 0; i < permiso.length; i++) {
console.log("List obtenido por el boton: " + permiso[i]);
}
var RolPermisos = { rolId: $("#IdRol").val() , permisos: permiso };
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: '../../Roles/api/Ui/',
dataType: 'json',
data: $.toJSON(lineItems),
success: function (result) {
if (result) {
alert('Success');
}
else {
alert('Failure');
}
}
});
}
})
My English is not so good, I hope you get the answer.
I have an ASP .NET application with multiple tabs on a view, each tab containing several inputs for each course attendee (name, phone number, job title, etc).
I created a jquery function to collect data from views and generate the JSON accordingly:
function getAttendees() {
var sections = [];
$(".divWithInputs").each(function (i, val) {
var tab = $(val).serializeArray();
sections.push(tab);
});
return sections;
}
And the submit function:
$("#checkoutAttendees").click(function () {
var formData = new FormData();
formData.append("Attendees", JSON.stringify(getAttendees()));
$.ajax({
url: "/controllerURL",
type: 'POST',
contentType: "application/json; charset=utf-8",
cache: false,
contentType: false,
processData: false,
data: formData,
success: function (response) {
alert(response);
}
});
});
I have an issue when reading the JSON, because I need an IEnumerable of Attendee objects to populate with this sort of data:
[
[
{
"name":"first-name-attendee-0",
"value":"Jon"
},
{
"name":"last-name-attendee-0",
"value":"Stark"
},
{
"name":"email-attendee-0",
"value":"jon.stark#northwall.com"
},
{
"name":"phone-attendee-0",
"value":"0181042981029840"
},
{
"name":"company-attendee-0",
"value":"Nightwatch"
},
{
"name":"job-title-attendee-0",
"value":"King"
}
],
[
{
"name":"first-name-attendee-1",
"value":"Aria"
},
{
"name":"last-name-attendee-1",
"value":"Stark"
},
{
"name":"email-attendee-1",
"value":"noemail#nodomain.com"
},
{
"name":"phone-attendee-1",
"value":"000000000000000"
},
{
"name":"company-attendee-1",
"value":"No organization"
},
{
"name":"job-title-attendee-1",
"value":"Killer"
}
],
[
{
"name":"first-name-attendee-2",
"value":"Mad"
},
{
"name":"last-name-attendee-2",
"value":"King"
},
{
"name":"email-attendee-2",
"value":"mad.king#yahoo.com"
},
{
"name":"phone-attendee-2",
"value":"019209840921840219"
},
{
"name":"company-attendee-2",
"value":"Kingdom"
},
{
"name":"job-title-attendee-2",
"value":"King"
}
]
]
Any advise on how to properly transform data from JSON into a list of Attendees ?
Thank you.
Solution: in backend I had to create a list of lists of NameValuePair
The Action method looks like this:
[HttpPost]
public ActionResult TrainingBook(FormCollection formCollection)
var viewModel = new TrainingFormViewModel();
var attendeesListJSON = formCollection["Attendees"];
var attendeesJson = JsonConvert.DeserializeObject<List<List<KeyValuePair<string, string>>>>(attendeesListJSON);
List<Attendees> attendees = new List<Attendees>();
foreach (var item in attendeesJson)
{
attendees.Add(new Attendees {
FirstName = item[0].Value,
LastName = item[1].Value,
WorkEmailAddress = item[2].Value,
PhoneNumber = item[3].Value,
Organization = item[4].Value,
JobTitle = item[5].Value
});
}
A key value pair is name and value for an input, the first list of key value pairs is one attendee, the the list of lists, ofc, all the attendees.
I have a simple json document :
[ {
"x" : "a",
"y" : 2
}, {
"x" : "b",
"y" : 8
}, {
"x" : "c",
"y" : 4
}, {
"x" : "d",
"y" : 15
} ]
I want to visualize it using Highcharts having 4 series. I could success, however, the data appeared only as one series (see the next Figure).
Here is part of the code:
var options = {
.
.
.
series: [{ }]
};
.
.
.
var data = JSON.parse(json);
var seriesData = [];
for (var i = 0; i < data.length; i++) {
seriesData.push([data[i].x, data[i].y]);
options.xAxis.categories.push( data[i].x );
}
options.series[0].data = seriesData;
var chart = new Highcharts.Chart(options);
also updating the series
chart.series[0].update({
type: type,
});
works fine.
using
options.series.push({name: data[i].x, data: [data[i].x, data[i].y]});
creates 4 series but not appropriately visualized and also updating the series
chart.series[0].update({
type: type,
});
doesn't work, therefore, I want to focus in the first mentioned method.
any hints?
EDit: code which partially works for me:
var options = {
chart: {
renderTo: 'container',
type: 'column' //default
},
title: {
text: ''
},
yAxis: {
title: {
enabled: true,
text: 'Count',
style: {
fontWeight: 'normal'
}
}
},
xAxis: {
title: {
enabled: true,
text: '',
style: {
fontWeight: 'normal'
}
},
categories: [],
crosshair: true
} ,
plotOptions: {
pie: {
innerSize: 125,
depth: 80
},
column: {
pointPadding: 0.2,
borderWidth: 0,
grouping: false
}
},
series: [{ }]
};
// Set type
$.each(['column', 'pie'], function (i, type) {
$('#' + type).click(function () {
chart.series[0].update({
type: type
});
});
var data = get the data fom json file**
var seriesData = [];
for (var i = 0; i < data.length; i++) {
seriesData.push([data[i].x, data[i].y]);
options.xAxis.categories.push( data[i].x );
}
options.series[0].data = seriesData;
var chart = new Highcharts.Chart(options);
});
});
You have to decide whether you want to have 4 different series and update all 4 series at once or you want to have one series an then build e.g. legend on your own.
If you want to have 4 series, set grouping to false, set xAxis categories and each point should be mapped to one series with one point - the point.x should have the index of the series.
const series = data.map((point, x) => ({ name: point.x, data: [{ x, y: point.y }]}))
const chart = Highcharts.chart('container', {
chart: {
type: 'column'
},
plotOptions: {
column: {
grouping: false
}
},
xAxis: {
categories: data.map(point => point.x)
},
series: series
});
Then you can update your all 4 series:
chart.series.forEach(series => series.update({
type: series.type === 'column' ? 'scatter' : 'column'
}, false))
chart.redraw()
example: http://jsfiddle.net/pdjqrj5y/
I want to be able to change the min and max values in the Kendo RadialGauge "on the fly" with ajax. Do I need to destroy the gauge first and create a new one, or could I possibly just change current gauge and redraw it with min, max, and pointer values?
I have a typical gauge using Razor engine:
#(Html.Kendo().RadialGauge()
.Name("TotalCostGauge")
.Pointer(pointer => pointer.Value(0))
.Scale(scale => scale
.MinorUnit(5)
.StartAngle(-50)
.EndAngle(230)
.Max(100)
.Labels(labels => labels.Position(GaugeRadialScaleLabelsPosition.Inside))
.Ranges(ranges =>
{
ranges.Add().From(180).To(180).Color("#c20000");
}
)
)
)
Using ajax I want to be able to update those values:
$.ajax({
type: "GET",
dataType: "json",
url: 'Controller/GetStuff/',
success: function (data) {
var totalCostGauge = $("#TotalCostGauge").data("kendoRadialGauge");
var totCostOptions = totalCostGauge.options;
//TODO: I want to be able to do something like this
totCostOptions.scale.max = data.Max;
totalCostGauge.value(data.TotalCost);
totalCostGauge.redraw();
},
error: function (error) {
}
});
I went through the documentation and could not see that the Min and Max values could be changed, however the pointer value can be changed via ajax.
Eventually I found out that I was going at this all wrong. This is actually what I needed to do:
$.ajax({
type: "GET",
dataType: "json",
url: 'Controller/GetStuff/',
success: function (data) {
$("#TotalCostGauge").kendoRadialGauge({
scale: {
max: data.Max, // This is actually what I should have done :)
startAngle: -50,
endAngle: 230,
labels: {
format: "C0",
font: "8px Arial,Helvetica,sans-serif"
},
ranges: [{
from: 0,
to: 0,
color: "green"
}]
}
});
var totalCostGauge = $("#TotalCostGauge").data("kendoRadialGauge");
totalCostGauge.value(data.Cost);
totalCostGauge.redraw();
},
error: function (error) {
}
});
Am trying to plot Spline graph using data fetched from MySQL.
<script>
var chart;
function requestData()
{
$.ajax({
url: 'get_hourly_data.php',
datatype: "json",
success: function(data)
{
chart.series[0].addPoint(data);
},
});
}
$(document).ready(function() {
Highcharts.setOptions({
global: {
useUTC: false
}
});
chart = new Highcharts.Chart({
chart: {
renderTo: 'graph',
type: 'spline',
events: {
load: requestData
}
},
title: {
text: 'Monitoring'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'Response time (ms)',
margin: 80
}
},
series: [{
name: 'Time',
data: [],
}]
});
});
</script>
get_hourly_data.php
<?php
// Query to fetch half an hour data from current time
$query = "SELECT UNIX_TIMESTAMP(current_ts), response_time FROM site_response WHERE current_ts >= DATE_SUB( NOW( ) , INTERVAL 30 MINUTE ) AND site_id ='2'";
$result = mysql_query($query,$db);
while($item = mysql_fetch_array($result))
{
$current_time = $item['UNIX_TIMESTAMP(current_ts)']*1000;
$response_time = $item['response_time']*1;
$ret = array($current_time, $response_time);
echo json_encode($ret);
}
?>
My JSON data looks like this
[1357536877000,0.012178182601929][1357536881000,0.0123610496521][1357536891000,0.011971950531006][1357536895000,0.011821985244751][1357536916000,0.010467052459717]
If I limit only one return value by replacing query mentioned below in get_hourly_data.php am able to plot graph with one value but not for group of values. Requirement is to fetch half an hour data from now and plot spline chart.
$query = "SELECT UNIX_TIMESTAMP(current_ts), response_time FROM site_response WHERE current_ts >= DATE_SUB( NOW( ) , INTERVAL 30 MINUTE ) AND site_id ='2' limit 1";
I suppose am doing something wrong when adding server data to graph .Probably after jQuery success function .Am first time stackoverflow user and new to jQuery. Could someone please guide me?
Posting code which works perfectly.
<script>
var chart;
function requestData()
{
$.ajax({
url: 'get_hourly_data.php',
datatype: "json",
success: function(data)
{
chart.series[0].setData(data);
},
});
}
$(document).ready(function() {
Highcharts.setOptions({
global: {
useUTC: false
}
});
chart = new Highcharts.Chart({
chart: {
renderTo: 'graph',
type: 'spline',
events: {
load: requestData
}
},
title: {
text: 'Monitoring'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'Response time (ms)',
margin: 80
}
},
series: [{
name: 'Time',
data: [],
}]
});
});
</script>
get_hourly_data.php:
$ret = array();
while($item = mysql_fetch_array($result))
{
$current_time = $item['UNIX_TIMESTAMP(current_ts)']*1000;
$response_time = $item['response_time']*1;
$y = rand(0, 100);
$ret[] = array($current_time, $response_time);
}
echo json_encode($ret);
You are echoing inside the while loop. You need to create an array of array for the data.
You need your JSON to look like
[[1357536877000,0.012178182601929],[1357536881000,0.0123610496521],[1357536891000,0.011971950531006],[1357536895000,0.011821985244751],[1357536916000,0.010467052459717]]
Something like this may work
$dataArr=new array();
while($item = mysql_fetch_array($result))
{
$current_time = $item['UNIX_TIMESTAMP(current_ts)']*1000;
$response_time = $item['response_time']*1;
$dataArr[] = array($current_time, $response_time);
}
echo json_encode($dataArr);
$query = "SELECT UNIX_TIMESTAMP(current_ts) * 1000, response_time FROM site_response WHERE current_ts >= DATE_SUB( NOW( ) , INTERVAL 30 MINUTE ) AND site_id ='2'";
$dataArr = new array();
while($item = mysql_fetch_array($result))
{
$current_time = $item['UNIX_TIMESTAMP(current_ts)'];
$response_time = $item['response_time'];
$dataArr[] = array($current_time, $response_time);
}
echo json_encode($dataArr);
On success function
success: function(data)
{
data = jQuery.parseJSON(data);
chart.series[0].addPoint(data);
}