Datatable Editor's "new" form posts empty values - ajax

after one week of search/tests/debugging and headaches... I'm kindly seeking your help on the following problem: Consider the following simple piece of code (I'm focusing on the POST only):
var editor = new $.fn.dataTable.Editor( {
ajax: {
create: {
type: 'POST',
url: '/employees'
},
edit: {
type: 'PUT',
url: 'XXXXXXXX'
},
remove: {
type: 'DELETE',
url: 'XXXXXXXX'
}
},
table: "#example",
fields: [ {
label: "First name:",
name: "first_name"
}, {
label: "Last name:",
name: "last_name"
}, {
label: "Position:"
name: "position"
}
]
} );
$('#example').DataTable( {
dom: "Bfrtip",
ajax: "/employees",
columns: [
{ data: "first_name" },
{ data: "last_name" },
{ data: "position" },
],
select: true,
buttons: [
{ extend: "create", editor: editor },
{ extend: "edit", editor: editor },
{ extend: "remove", editor: editor }
]
} );
When I submit the form, it posts empty values for the 3 fields! Do I need to serialize Editor's form fields?
I'm using Laravel as PHP MVC The related "#example" datatables displays data correctly, no problem on that.
I just want to use the client side Datatable...
Thanks a lot for your help!

Actually the form is posting values... However I get them as "urlencode" and can't use them in my controller... Will post another question...

Related

Is it possible to add data when posting with ajax in tabulator5?

I am using codeigniter4.
In the current environment, the csrf token must be included in the post data when making an ajax request.
I understand adding get parameters, but is it possible to add post data?
//Build Tabulator
var table = new Tabulator("#example-table", {
height: "311px",
layout: "fitColumns",
ajaxURL: "user/test/ajaxtest/",
ajaxParams :{ key1 : "value1" , key2 : "value2" },
ajaxType:"POST",
progressiveLoad: "scroll",
paginationSize: 20,
placeholder: "No Data Set",
columns: [{
title: "Name",
field: "name",
sorter: "string",
width: 200
},
{
title: "Progress",
field: "progress",
sorter: "number",
formatter: "progress"
},
{
title: "Gender",
field: "gender",
sorter: "string"
},
{
title: "Rating",
field: "rating",
formatter: "star",
hozAlign: "center",
width: 100
},
{
title: "Favourite Color",
field: "col",
sorter: "string"
},
{
title: "Date Of Birth",
field: "dob",
sorter: "date",
hozAlign: "center"
},
{
title: "Driver",
field: "car",
hozAlign: "center",
formatter: "tickCross",
sorter: "boolean"
},
],
});
Anyone know please.
You could use ajaxRequestFunc to do this.
Refer to the documentation here. Using this, you could process your ajax request however you would prefer and just return the data to the table.
You could raise a POST request with params in your custom ajax call using ajaxRequestFunc
Try this.
$.ajax({
url: '/controller/method',
type: 'POST',
data: {
'csrf_test_name': '<?= csrf_token() ?>',
'param1': 'value1',
'param2': 'value2'
},
success: function(response) {
console.log(response);
}
});
In this example, csrf_token is the token you obtained from CodeIgniter's function, and 'param1' and 'param2' are the additional post data you want to send to the server.
You can access these post data in your CodeIgniter controller using the $this->request->getPost('param1') and $this->request->getPost('param2') functions. Don't forget to include the 'csrf_test_name' parameter in your post data to pass the CSRF token.

How to sync my Store when I update the bounded record using form (onUpdateClick). I'm using Extjs 7.5 (Sencha CMD)

This is my first time using a javascript framework, I would like to implement MVVM in my EXT JS application and the data is coming from my WEB API (ASP.NET FRAMEWORK).
My problem is that, I don't seem to understand how to fully use viewModel which looks up to my store. I successfully bound my ViewModel in my grid but now I don't know how to update the selected record using a form (modal) and sync my store (send update request through API)
I have a feeling that I'm doing it the wrong way. I don't know how to do this in fiddle so I'll just paste my code here.
Genre.js [Model]
Ext.define('VAM2.model.Genre', {
extend: 'VAM2.model.Base',
alias: 'model.genre',
fields: [
{name: 'GenreId', type: 'int'},
{name: 'Code', type: 'string'},
{name: 'CreatedBy', type: 'string'},
]
});
Genre.js [Store]
Ext.define('VAM2.store.Genre', {
extend: 'Ext.data.Store',
alias: 'store.genre',
model: 'VAM2.model.Genre',
autoLoad: false,
pageSize: 10,
storeId: 'GenreId',
proxy : {
type : 'rest',
actionMethods : {
read : 'GET'
},
cors:true,
url: 'https://localhost:44332/api/Genre/GetGenresExtJs',
api:{
create: 'https://localhost:44332/api/Genre/CreateGenreExtJS',
read: 'https://localhost:44332/api/Genre/GetGenresExtJs',
update: 'https://localhost:44332/api/Genre/EditGenreExtJS',
destroy: 'https://localhost:44332/api/Genre/CreateGenreExtJS'
},
useDefaultXhrHeader: false,
reader: {
type : 'json',
headers: { 'Accept': 'application/json' },
allDataOptions: {
associated: true,
persist: true
},
rootProperty : 'data',
totalProperty: 'total'
},
}
});
GenreViewModel.js - I'm not sure if this is okay but the read is working
Ext.define('VAM2.view.genre.GenreViewModel', {
extend: 'Ext.app.ViewModel',
alias: 'viewmodel.genre',
requires:[
'VAM2.model.Genre'
],
stores: {
myGenres : {
model: 'VAM2.model.Genre',
autoLoad: true,
proxy : {
type : 'rest',
actionMethods : {
read : 'GET'
},
cors:true,
url: 'https://localhost:44332/api/Genre/GetGenresExtJs',
api:{
create: 'https://localhost:44332/api/Genre/CreateGenreExtJS',
read: 'https://localhost:44332/api/Genre/GetGenresExtJs',
update: 'https://localhost:44332/api/Genre/EditGenreExtJS',
destroy: 'https://localhost:44332/api/Genre/CreateGenreExtJS'
},
useDefaultXhrHeader: false,
reader: {
type : 'json',
headers: { 'Accept': 'application/json' },
allDataOptions: {
associated: true,
persist: true
},
rootProperty : 'data',
totalProperty: 'total'
},
}
}
},
data:{
title:'Sample Binding'
},
formulas: {
currentRecord: {
bind: {
bindTo: '{groupGrid.selection}', //--> reference configurated
//--> on the grid view (reference: groupGrid)
deep: true
},
get: function(record) {
return record;
},
set: function(record) {
if (!record.isModel) {
record = this.get('records').getById(record);
}
this.set('currentRecord', record);
}
}
}
});
View -- This is where it gets confusing. I don't know how to put the bounded data from grid to a form modal and then save and sync my store.
Ext.define('VAM2.view.genre.GenreList', {
extend: 'Ext.container.Container',
xtype: 'myGenreList',
requires: [
'VAM2.view.genre.GenreController',
'VAM2.view.genre.GenreViewModel',
'Ext.grid.column.Boolean',
'Ext.form.field.Checkbox',
'Ext.form.field.TextArea',
'Ext.form.field.Text'
],
controller: "genre",
viewModel: {
type: "genre"
},
width:'100%',
layout: {
type: 'vbox',
pack: 'start',
align: 'stretch'
},
style: {
backgroundColor: '#f5f5f5'
},
items: [{
xtype: 'grid',
reference: 'groupGrid', //--> used in the viewmodel,
bind: {
title: '{title}',
store: '{myGenres}'
},
columns: [{
text:'GenreIdField',
id:'GenreIdField',
dataIndex:'GenreId',
hidden:true
},{
text: 'Code',
dataIndex: 'Code',
flex:1
}, {
text: 'Created By',
dataIndex: 'CreatedBy',
flex: 1
}],
listeners:{
select:'onGenreSelected_FORMA' //--> I'm thinking this will trigger
//-> a form (modal) containing the data to update
}
}]
});
A fiddle example would be great! Thank you!
Screenshot:
This is where I would like to display form modal that can sync/update my store when I modify some data.
To do store.sync() you need to set values on the record first.
Example is without ViewModel:
https://fiddle.sencha.com/#fiddle/3isg&view/editor
select: function (grid, record) {
console.log(record);
let win = Ext.create("Ext.window.Window", {
title: 'Edit',
modal: true,
autoShow: true,
width: 400,
height: 500,
controller: {},
items: [{
xtype: 'form',
reference: 'form',
fieldLabel: 'name',
items: [{
xtype: 'textfield',
name: 'name'
}]
}],
buttons: [{
text: 'cancel',
handler: function () {
win.close();
}
}, {
text: 'save',
handler: function () {
var values = this.lookupController().lookup('form').getValues();
record.set(values);
grid.getStore().sync({
scope: this,
success: function () {
win.close();
Ext.toast({
html: 'Well done',
align: 't'
});
},
failure: function () {
Ext.toast({
html: 'Problem occurred',
align: 't'
});
}
});
}
}],
listeners: {
afterrender: function () {
this.lookupController().lookup('form').loadRecord(record);
}
}
})
}

How to parse my JSON data to String in KENDO GRID?

how can i format this object Object to its actual values ?
I want this json object to display its actual values in a specific kendo grid column .
Can someone please help me and teach me how to do it ?
This is the image of the kendo grid with the result ,
While here is the code that I am using in my view .
Can please someone help .
contact : new kendo.data.DataSource({
transport:{
read:{
type: "GET",
url:"reservation/list",
dataType:"json",
contentType: "application/json; chartset=utf-8"
},
update: {
url: "contacts/update",
dataType: "json",
type: "POST"
},
destroy: {
url: "contacts/destroy",
dataType: "json",
type:"POST"
},
create: {
url: "contacts/store",
dataType: "json",
type:"POST"
}
},
schema:{
model:{
id:"id",
fields:{
Purpose:
{
type:"string",
validation:{required:true}
},
RoomID:
{
from: "RoomID.room_name",
type: "string"
},
Equipments:
{
from: "Equipments",
type: "string"
},
start:
{
type:"date",
validation:{required:true}
},
end:
{
type:"date",
validation:{required:true}
},
}
}
},
pageSize:10
}),
init : function(e){
$("#grid").kendoGrid({
dataSource: this.contact,
selectable: true,
height:600,
editable: "popup",
filterable: true,
sortable: {
mode: "multiple",
allowUnsort: true,
showIndexes: true
},
toolbar: ["search"],
columns: [
{
field: "Purpose",
title:"Purpose"
},
{
field: "RoomID",
title:"Room",
},
{
field: "Equipments",
title:"Equipments",
},
{
field: "start",
title:"Start",
//template: '#= kendo.toString(kendo.parseDate(start), "MM/dd/yyyy HH:mm:ss")#'
format: "{0:MMM dd,yyyy hh:mm tt}",
parseFormats: ["yyyy-MM-dd'T'HH:mm.zz"]
},
{
field: "end",
title:"End",
//template: '#= kendo.toString(kendo.parseDate(end), "MM/dd/yyyy HH:mm:ss")#'
format: "{0:MMM dd,yyyy hh:mm tt}",
parseFormats: ["yyyy-MM-dd'T'HH:mm.zz"]
},
{
command: ["edit", "destroy"],
title: " ",
width: "250px"
}
],
pageable:{
pageSize:10,
refresh:true,
buttonCount:5,
messages:{
display:"{0}-{1}of{2}"
}
}
});
},
});
kendo.bind($("#whole"),model);
model.init();
Hopefully this will help you out with templating out the results.
https://dojo.telerik.com/ICOceLUj
In the example above I have created a custom column that takes the incoming row object and then parsed the name of the item and the category object into a single template.
To achieve this I have added the template property and used a function with an external template script to handle the manipulation. I personally find this easier to manage than trying to inline a complex client template (especially if you have logic involved)
So this is how we set it up initially:
{ title: "custom template", template:"#=customTemplate(data)#" }
obviously you will change it to the property you need to look at in your model.
then the function is a couple of lines of code:
function customTemplate(data){
var template = kendo.template($('#customTemplate').html());
var result = template(data);
return result;
}
so this takes the customTemplate template i have created for this and renders it as html and then it will apply the data where appropriate. The template looks like this:
<script id="customTemplate" type="text/x-kendo-template">
<div>
<h5> #:data.ProductName#</h5>
<h4>#: JSON.stringify(data.Category, null, 4) #</h4>
</div>
</script>
You can then customize this template to how you need it to look for your specific needs. You can then either create a source template for the items and then map the values back as single string or have the logic for this in the template. Which ever is most sensible in your case.
For more info on templating please look at this link:
https://docs.telerik.com/kendo-ui/framework/templates/overview
You can use kendo.stringify in your column template.
Example:
kendo.stringify(YourProperty)

Kendo Grid Serverside Paging, Incorrect Parameter Map values

I'm trying to use the Dynamic Linq Helper libraries from Kendo. The parameter map function on the grid does not have the correct parameters to send to the controller.
The parameterMap options have:
{"take":10,"skip":0,"page":1,"pageSize":10}
but according to the example, it should have take, skip, sort, filter, which is not in the parameterMap function or getting passed to the server.
I'm following the example here
http://www.telerik.com/blogs/kendo-ui-open-sources-dynamic-linq-helpers
And also looked other examples, my grid is set up the same as the others.
The only difference being, this is a Web API single page app, not MVC. However, this shouldn't make a difference in what the Grid class is passing to it's parameterMap function.
What is going on here?
$("#grid").kendoGrid({
dataSource: {
transport: {
read: {
url: "http://localhost/biahost/query/projectStatuses",
dataType: "application/json",
type: "POST",
contentType: "application/json; charset=utf-8"
//data:{}
},
parameterMap: function (options) {
debugger;
//options only contain {"take":10,"skip":0,"page":1,"pageSize":10}
return kendo.stringify(options);
}
},
schema: {
data: "Data",
total: "Total",
model: {
fields: {
NAME: { type: "string" },
CODE: { type: "string" },
STATUS: { type: "string" },
COMMENTS: { type: "string" },
INSERTS: { type: "string" },
UPDATES: { type: "string" },
TOTAL_UPDATES: { type: "string" },
LAST_ACTION_DATE: { type: "string" }
//UnitId: { type: "string" },
//UnitName: { type: "string" }
}
}
},
pageSize: 10,
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
filterable: true,
sortable: true,
pageable: true,
columns: projectStatusColumns
});
var projectStatusColumns = [
{
field: 'NAME',
label: 'Res name',
hidden: true,
},
{
field: 'CODE',
label: 'Code'
},
{
field: 'STATUS',
label: 'Status'
},
{
field: 'COMMENTS',
label: 'Comments'
}
,
{
field: 'INSERTS',
label: 'Inserts'
}
,
{
field: 'UPDATES',
label: 'Updates'
}
,
{
field: 'TOTAL_UPDATES',
label: 'Total Updates'
}
,
{
field: 'LAST_ACTION_DATE',
label: 'Last Action Date'
}
];
had the same problem so i looked it up and here i am. You just need to return "options" which contains the parameter map as it is, if you stringify it will become a json object which cannot be defined in a url.
Hope i'm not too late!

Kendo Grid renders properly but does not display json data

I have been having a tough time with grids lately, mostly getting them to display properly formatted JSON data that is being fetched from a webservice (which has been checked in VS2013, and JSONLint), if a second set of eyes could please have a look at my solution and tell me whats lacking? I am going bananas!
function SetTelerikGrid() {
// prepare the data object and consume data from web service,...
$.ajax({
type: "GET",
async: false,
url: "http://localhost:38312/SDMSService.svc/GetProductPositionsByLocation/0544",
datatype: "json",
success: function (ProductData, textStatus, jqXHR) {
// populate kendo location grid by data from successful ajax call,...
$("#LocationProductsGrid").kendoGrid({
dataSource: {
data: ProductData, // solution here was: **JSON.parse(LocationData)**
schema: {
model: {
fields: {
Date: { type: "string" },
ProductCode: { type: "string" },
StoreNum: { type: "string" },
ProductQty: { type: "int" }
}
}
},
pageSize: 20
},
height: 550,
scrollable: true,
sortable: true,
filterable: true,
pageable: {
input: true,
numeric: false
},
columns: [
{ field: "Date", title: "Date", width: "130px" },
{ field: "ProductCode", title: "Product Code", width: "130px" },
{ field: "StoreNum", title: "Store Number", width: "130px" },
{ field: "ProductQty", title: "Product Qty", width: "130px" }
]
});
}
});
}
There is a breaking change in ASP.NET Core, related to how the JSON serializer
works
You can probably mitigate this by adding a json option like this:
1:
change
services.AddMvc();
to
services
.AddMvc()
.AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
OR
2:
public IActionResult Read()
{
// Override serializer settings per-action
return Json(
MyModel,
new JsonSerializerSettings { ContractResolver = new DefaultContractResolver() }
);
}
refrences :
http://www.telerik.com/forums/using-2016-2-630-preview---data-not-displayed#qlHR6zhqhkqLZWuHfdUDpA
https://github.com/telerik/kendo-ui-core/issues/1856#issuecomment-229874309
https://github.com/telerik/kendo-ui-core/issues/1856#issuecomment-230450923
Finally figured it out, the 'ProductData' field - although in perfect JSON format - still required to be parsed as JSON in the datasource configuration, like so,...
Data: JSON.parse(ProductData)

Resources