Try loading data from JSON using JsGrid MVC - json

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"

Related

Update Chart.js data with ajax

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: []
}]
}
});

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

SharePoint data does not display in Kendo Scheduler

Data is retrieved using the REST call in my transport, but the event does not display in Kendo Scheduler. I am interested in only displaying data at this point, the update is not working
$("#scheduler").kendoScheduler({
date: new Date("2018/11/11"),
startTime: new Date("2018/11/11 07:00 AM"),
height: 600,
views: [
"day",
"workWeek",
"week",
{ type: "month", selected: true },
"agenda",
{ type: "timeline", eventHeight: 50}
],
add: function (e) {
},
change: function (e) {
},
error: function (e) {
//TODO: handle the errors
alert(e.errorThrown);
},
dataSource: {
transport: {
read: {
url: "https://SharePoint URL/apps/crp/_api/web/lists/getbytitle('list name')/items?$expand=Author&$select=Author/Id,Author/Title,Title,Start1,OData__x0045_nd1,RecurrenceRule,RecurrenceParentID,CategoryDescription,IsAllDay&$filter=Start1 ge datetime'2018-11-01T00:00:00Z'",
beforeSend: function (xhr) {
xhr.setRequestHeader("Accept", "application/json; odata=verbose");
}
},
add: function (e) {
},
error: function (e) {
//TODO: handle the errors
alert(e.errorThrown);
},
update:
{
url: function (data) {
alert('updating');
return "https://SharePoint URL/_api/web/lists/getbytitle(listname)/items" + "(" + data.ID + ")";
},
type: "POST",
dataType: "json",
contentType: "application/json;odata=verbose",
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"If-Match": "*",
"X-HTTP-Method": "MERGE",
},
},
parameterMap: function (data, type) {
if (data.models) {
alert(kendo.stringify(data.models));
return {
models: kendo.stringify(data.models)
}
}
}
},
schema: {
model: {
id: "ID",
fields: {
ID: { from: "ID", type: "number" },
title: { from: "Title", defaultValue: "No title", validation: { required: true } },
start: { type: "date", from: "Start1" },
end: { type: "date", from: "OData__x0045_nd1" },
recurrenceRule: { from: "RecurrenceRule" },
recurrenceId: { from: "RecurrenceParentID", type: "number" },
description: { from: "CategoryDescription" },
isAllDay: { type: "boolean", from: "IsAllDay" } //,
}
}
}
}
});
Reviewing the JSON call, data is retrieved properly but does not display in the Scheduler. I tried capturing events in the datasource, that does not look like it is processed, so the datasource does not seem to populate (change or add events).
Data returned looks like this after JSON call:
"{\"d\":{\"results\":[{\"__metadata\":{\"id\":\"Web/Lists(guid'2abecf66-35ed-4c67-b1f1-8b7255ebf0e2')/Items(1)\",\"uri\":\"https://SharePoint url/_api/Web/Lists(guid'2abecf66-35ed-4c67-b1f1-8b7255ebf0e2')/Items(1)\",\"etag\":\"\\"4\\"\",\"type\":\"SP.Data.6001C5110ListItem\"},\"Author\":{\"__metadata\":{\"id\":\"43c25e84-bf91-4d7d-951f-c480d9b2173f\",\"type\":\"SP.Data.UserInfoItem\"},\"Id\":5,\"Title\":\"SP USer\"},\"Title\":\"6001-C5-110\",\"Start1\":\"2018-11-14T15:00:00Z\",\"OData__x0045_nd1\":\"2018-11-14T17:00:00Z\",\"RecurrenceRule\":null,\"RecurrenceParentID\":null,\"CategoryDescription\":\"My Description\",\"IsAllDay\":null}]}}"
Added data: to the schema section of the datasource, thank you Sandun for pointing me in right direction, I defined the model for the scheduler without specifying the data.
schema: {
data: function (data) {
return data.d && data.d.results ? data.d.results : [data.d];
},
model: {
id: "ID",
fields: {
ID: { from: "ID", type: "number" },
title: { from: "Title", defaultValue: "No title", validation: { required: true } },
start: { type: "date", from: "Start1" },
end: { type: "date", from: "OData__x0045_nd1" },
recurrenceRule: { from: "RecurrenceRule" },
recurrenceId: { from: "RecurrenceParentID", type: "number" },
description: { from: "CategoryDescription" },
isAllDay: { type: "boolean", from: "IsAllDay" } //,
// startTimeZone: "Etc/UTC",
// endTimeZone: "Etc/UTC"
// description: { from: "Description" }
}
}
}

How to send array with json using ajax

How do I send an array with json using ajax? I want to store email and name:
$.ajax({
url: 'index.php?route=module/newsletters/news',
type: 'post',
data: 'email=' + $('#txtemail').val() ,
dataType: 'json',
success: function(json) {
alert(json.message);
}
});
Let's suppose you have an array?
var array = [
"student1" : {
"name": "jon",
"email": "test#example.com"
},
"student2" : {
"name": "jon2",
"email": "test2#example.com"
}
]
$.post('index.php?route=module/newsletters/news', {
data : JSON.stringify(array),
datatype : 'application/json',
}, function(success) {
console.log(success)
});
Your question is not clear.please write your question in correct format.then community can be resolve your question easily.
I assume your problem and give solution for that.
var array = {name:'dua',email:'dua#gmail.com'};
$.post('index.php?route=module/newsletters/news', {
data : JSON.stringify(array)
}, function(success) {
console.log(success)
});
var postData = { "email":email,"name":name }
$.ajax({
url: 'index.php?route=module/newsletters/news',
type: 'post',
data: postData,
dataType: 'json',
success: function(json) {
alert(json.message);
}
});

Kendo UI Grid with object ID translation

I'm trying to make a grid with KendoUI with external data via JSON (php+mysql engine) from TABLE A and one of columns of these data, get text labels from another TABLE B.
Example, data are: idPermission=1, user_id=1, business_unit_id=1, permission=10
The user_id=1 I want get from another table (Users) their names, 1=John Doe, 2=Martin Brown.
I want to see "John Doe" instead id 1 in the visualization of grid, and "Martin Brown" instead id 2. When inline (or popup) editing of the records I've already reached the target, and I've a select box with the names and not the ids!
Here is my code:
<script>
$(function() {
var crudServiceBaseUrl = "http://localhost/ajax/";
var dataTable = "UsersPermissions";
// This is the datasource of the grid
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "table_action.php?op=R&tbl="+dataTable,
dataType: "json"
},
update: {
url: crudServiceBaseUrl + "table_action.php?op=U&tbl="+dataTable,
type: "POST"
},
destroy: {
url: crudServiceBaseUrl + "table_action.php?op=D&tbl="+dataTable,
type: "POST"
},
create: {
url: crudServiceBaseUrl + "table_action.php?op=C&tbl="+dataTable,
type: "POST"
}
},
batch: true,
pageSize: 10,
schema: {
model: {
id: "idPermission",
fields: {
idPermission: { editable: false, nullable: true },
user_id: { validation: { required: true } },
business_unit_id: {},
permission: { validation: { required: true } },
}
}
}
});
// This is the datasource of the user_id column
usersSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "table_action.php?op=R&tbl=Users",
dataType: "json"
}
},
batch: true,
schema: {
model: {
id: "idUser",
fields: {
idUser: {},
email: {},
password: {},
name: {},
last_login: {},
status: {}
}
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
pageable: true,
sortable: {
mode: "single",
allowUnsort: false
},
reorderable: true,
resizable: true,
scrollable: false,
toolbar: ["create"],
columns: [
{
field: "user_id",
editor: function (container, options) { // This is where you can set other control types for the field.
$('<input name="' + options.field + '"/>').appendTo(container).kendoComboBox({
dataSource: usersSource,
dataValueField: "idUser",
dataTextField: "name",
});
},
title: "ID Utente"
},
{ field: "business_unit_id", title: "Business Unit"},
{ field: "permission", title: "Permission"},
{ command: ["edit", "destroy"], width: "230px"}],
editable: "inline"
});
});
</script>
How I can make the same thing I've done in editing mode, in view mode?
For achieving that you have to first edit the query of the read operation seeing your sample data it must be like this
SELECT a.idPermission, b.name, a.business_unit_id, a.permission
FROM TABLE_A AS a
JOIN TABLE_B(users) AS B ON a.user_id=b.user_id;
json encode the data and send to client
and in your kendo grid change column user_id to name
I know you were asking about the HTML/JavaScript way, but using MVC, this is a good, alternative way to do it:
http://decisivedata.net/kendo-ui-grid-and-entity-framework-code-first-foreign-key-fields/