Update Chart.js data with ajax - json

I want to update my chart with ajax and Flask but
I can not update the data:
var chart = new Chart(canvas, {
type: "line",
datasets: [{
label: 'My Dataset',
}]
})
$(document).ready(function () {
$.ajax({
dataType: "text",
contentType: "application/json",
url: '{{ url_for("data_page") }}',
type: "post",
data: JSON.stringify({
timeDelta: "7",
technologie: "Java",
}),
success: function (data) {
let json = $.parseJSON(data); ==> [["2021-06-04", "2021-06-05"],[47, 3]]
chart.data.labels.push(json[0]); ==> It seems to work
chart.data.datasets[0].data = json[1]; ==> here I get : "Cannot set property 'data' of undefined"
chart.update();
}
});
});
I don't understand ,
where am I wrong ?
Thanks for any help !

It doesn't work because you initially create the chart with wrong configuration. The labels and datasets arrays must be contained in a data object.
Try this instead:
var chart = new Chart(canvas, {
type: 'line',
data: {
labels: [],
datasets: [{
label: 'My Dataset',
data: []
}]
}
});

Related

Highcharts with ajax/ json and SQL Server ASP.NET

I am new to Highcharts and Json data. I am trying to draw pretty simple column chart but failing to do so. below is my code.
HTML:
<div id="container"></div>
Javascript:
$(document).ready(function () {
$.ajax({
url: 'HighCharts.aspx/GetServices',
type: 'POST',
async: true,
dataType: 'json',
contentType: 'application/json',
data: '{}',
success: function (response) {
DrawServices(response.d);
},
error: function () {
window.open("ErrorPage.aspx", "_self")
}
});
});
function DrawServices(data) {
debugger;
if (data == null) {
window.open("ErrorPage.aspx","_self")
}
else {
$('#container').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Services Data'
},
xAxis: {
categories: data[0].Name
},
yAxis: {
title: {
text: 'Total Servcies Requested'
}
},
series: data[0].Total
});
}
}
JSON response
[{"Name":"Access the company internet","Total":489},{"Name":"Application Enhancement","Total":97},{"Name":"Catering Service","Total":250},{"Name":"Desktop","Total":350},{"Name":"Development and Consultation","Total":566},{"Name":"Email","Total":175},{"Name":"Laptop","Total":200},{"Name":"Maintenance","Total":32},{"Name":"Push Email","Total":700},{"Name":"Vehicle Sticker","Total":1200}]
Please guide me what i am doing wrong. blank chart is displaying
You can set x-axis type to category and map your data to the format required by Highcharts, for example: [point.name, point.y]
xAxis: {
type: 'category'
},
series: [{
data: data.map(el => [el.Name, el.Total])
}]
Live demo: http://jsfiddle.net/BlackLabel/r709soxe/
API Reference:
https://api.highcharts.com/highcharts/xAxis.type
https://api.highcharts.com/highcharts/series.column.data

Prevent Kendo Grid from auto saving

How can I stop the kendo grid/datasource automatically posting changes to the server?
I've tried intercepting Grid's saveChanges but it isn't being triggered by the Updated command. As per the docs, DataSource's auto-sync by default should be false, but I went ahead and set it anyway but to no effect.
$("#items-grid").kendoGrid({
dataSource: {
autoSync: false,
type: "json",
transport: {
read: {
url: "#Html.Raw(Url.Action("
ItemList ", "
PurchaseRequisition ", new {prId = #Model.Id }))",
type: "POST",
dataType: "json",
},
update: {
url: "#Html.Raw(Url.Action("
ItemEdit ", "
PurchaseRequisition "))",
type: "POST",
dataType: "json",
}
},
sync: function(e) {
console.log("sync complete");
},
schema: {
data: "Data",
total: "Total",
errors: "Errors",
model: {
id: "Id",
fields: {
/...
}
}
},
},
saveChanges: function(e) {
// not fired from Update command
e.preventDefault();
},
columns: [{
// ...
}, {
command: [{
name: "edit",
text: {
edit: "Edit",
update: "Update",
cancel: "Cancel"
}
}],
width: 100
}]
});
});
You can try with dataSource batch set to true.
var dataSource = new kendo.data.DataSource({
transport: {...},
batch: true
...}
$("#grid").kendoGrid({
dataSource: dataSource,
navigatable: true,
pageable: true,
height: 550,
toolbar: ["create", "save", "cancel"],
columns: [...],
editable: true
});
NOTE: this is inline editing.
You can see an example on the official page: Batch editing

Try loading data from JSON using JsGrid MVC

I have a problem loading data from JSON, when i assign the JSON to property "data" of JsGrid there are not data found in the table. I am retriving the data using Ajax.
$.ajax({
url: '#Url.Action("consulta_Unidades")',
async: false,
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (response) {
//console.log(response.value);
datos = JSON.stringify(response);
alert(datos);
}
});
The JsGrid code is next.
$("#table_div").jsGrid({
width: "100%",
height: "auto",
editing: true,
data: datos,
fields: [
{ name: "id_almacen", type: "text", width: 150 },
{ name: "idunidad", type: "text", width: 150 },
{ name: "tipo_unidad", type: "text", width: 150 },
{ name: "nomenclatura ", type: "text", width: 150 },
{ name: "capacidad_tarimas", type: "text", width: 150 },
{ name: "altura", type: "text", width: 150 },
{ type: "control" }
]
});
Any idea for resolve this problem?
In your ajax success "response" its a json object, only check
if(response){
datos=response
}
Another scenario:
The property "data" should be a "object" like json.
Change
datos = JSON.stringify(response);
For
datos = JSON.parse(response);
Use
datos = JSON.parse(JSON.stringify(response));
Only if it required for object "response"

How to send array of objects to a controller method?

I need your help, I have this piece of code in the controller side
public bool DraftMessage(message[] draftMessages, HttpPostedFileBase[] files = null)
{
return true;
}
and I use this client side code to send the data
function DraftMessage()
{
var myArray = [{ 'To': [1, 2], "Title": "Hello" }, { 'To': [1, 2], "Title": "Hello" }]
$.ajax({
type: "POST",
url: "#Url.Action("DraftMessage","Activities")",
datatype: "json",
traditional: true,
data: JSON.stringify({ draftMessages: myArray }),
beforeSend: function () { }
}).done(function (data) {});
}
$("input, select, textarea").change(function () { DraftMessage(); });
var contents = $('.note-editable').html();
$(".compose-message").on("blur", ".note-editable", function () {
if (contents != $(this).html()) {
DraftMessage();
contents = $(this).html();
}
});
but when I debug it I found that the array of messages in the controller is null so could anyone guide me about what I did wrong and help me to fix this issue.
You need to set contentType as "application/json"
function DraftMessage() {
var myArray = [{ 'To': [1, 2], "Title": "Hello" }, { 'To': [1, 2], "Title": "Hello" }];
$.ajax({
type: "POST",
url: "#Url.Action("DraftMessage","Home")",
contentType: "application/json",
data: JSON.stringify({ draftMessages: myArray })
}).done(function (data) {
console.log(data);
});
}
The default value of contentType header is "application/x-www-form-urlencoded" . Since we are sending the json stringified version of a a complex data structure, we should explicitly specify the contentType

Assign array of strings from JSON to Handsontables object in javascript?

I am trying to assign array of string to handsontables column as auto-complete. I am getting this JSON data from AJAX calls.
I am not getting to assign to source:. Please follow the code.
var loadBU = function(data) {
$.ajax({
url: "/EditInitiatives.svc/GetBUData",
data: "clientId=" + $value.val(),
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (res) {
data(res);
},
error: function (error) {
alert("Error: " + error.responseText);
}
});
};
$("#example2").handsontable({
data: getCarData(),
startRows: 7,
startCols: 4,
columns: [
{ data:'BusinessUnit',
type:'autocomplete',
source:loadBU(function(output){
var results = output.d
var arr = [], item;
for (var i = 0, len = results.length; i < len; i++) {
item = results[i];
arr.push([[item]]);
}
return arr;
}),
strict: true
},
]
});
It suppose to be like that EX: source: ["yellow", "red", "orange", "green", "blue", "gray", "black", "white"],
I don't understand how to assign array to source.
Reference
Your "return arr;" does not return to the "source:", it returns to the "loadBU" function.
For example, you could do:
success: function (res) {
var arr = data(res);
},
This is why it is not being assigned.
Try making your Ajax call before $("#example2").handsontable({ and save it to someVariable, then set the source: someVariable
Depending on what your Ajax call returns, you may also need to make some manipulations. For example, I needed to loop through and load into an array:
function AppendToArray(ajaxValues, theArray) {
for (var i = 0; i < ajaxValues.length; i++) {
theArray.push('' + ajaxValues[i].Text + '');
}
}
I hope this helps
I use it like this:
var workers = null;
$.ajax({
url: siteUrl + "/Worker/Get",
dataType: 'json',
type: 'GET',
cache: false
})
.done(function (data) {
$("#worker-grid").handsontable({
data: data,
rowHeaders: true,
colHeaders: ["internal<BR />identification", "name", "mobile", "e-mail address", "national<BR />identification", "partner", "source"],
colWidths: [100, 150, 100, 250, 150, 150, 100],
columns: [
{ data: "intId" },
{ data: "name" },
{ data: "mobile" },
{ data: "mail" },
{ data: "extId" },
{
data: "partner", type: 'dropdown', source: function (query, process) {
$.ajax({
url: siteUrl + "/Partner/Get",
dataType: 'json',
type: 'GET',
cache: false
})
.done(function (data) {
var values = [];
for (i in data) values.push(data[i].name);
process(values);
});
}
},
{ data: "source" }
],
columnSorting: true,
minSpareRows: 1
});
workers = $("#worker-grid").data("handsontable");
});
The key in assigning to the source is the process parameter in the source function.
I would like to add however that this approach will be fetching data from the server with every use. My example above uses a dropdown which does not make sense.. But it's the correct approach when using with autocompletion.