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

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.

Related

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)

Datatable Editor's "new" form posts empty values

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...

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)

Detecting server-side error when editing or creating Kendo Grid entries

I have an editable Kendo Grid to manage (create/modify) user accounts. Editing is done in a popup (versus inline or batch). I have client-side validation to help ensure that valid data is provided to the server, however I cannot figure out how to handle the response from the server in the event that the create/update fails server-side. I'm not talking 'failed' as in the request failed with a HTTP 404 or 500, for example; I'm talking failed as in the script on the server didn't like something about the data and refuses to oblige.
Can someone please show me how I can accomplish this? What I would like to be able to do is after the update is sent to the server, wait for the response. If the response says everything is OK, then great. If the response says something didn't go so well, I'd like to be able to (A) keep the popup editing window open and populated and (B) provide feedback to the user regarding the reason for the rejection. The data should not be committed to the grid unless the response says everything is OK. Likewise, the edit popup should remain open until the server says OK.
I'm flexible with how the server's response should be formatted, as long as I can accomplish what I want.
Before you direct me to the Kendo official API documentation, I am already well aware of it and refer to it daily. However, to say the least, it is incomplete and I cannot find anything relating to this topic. If you have found something in the documentation that you think could help me then by all means point me to the documentation =)
As requested, below is the code I have for creating the grid.
$("#kendo_user_grid").kendoGrid({
columns: [{
title: "Last name",
field: "lName"
},{
title: "First name",
field: "fName"
},{
title: "Business unit",
field: "businessUnit"
},{
title: "Username",
field: "loginId"
},{
title: "Email address",
field: "email"
},{
title: "Phone",
field: "phone"
},{
title: "Address",
field: "address"
},{
title: "City",
field: "city"
},{
title: "State",
field: "state"
},{
title: "Zip code",
field: "zipcode"
},{
title: "Country",
field: "country"
},{
title: "Time zone",
field: "timezone"
},{
title: "Privileges",
field: "privs"
},{
command: ["edit","destroy"],
title: " "
}],
scrollable: false,
dataSource: {
transport: {
read: {
url: "manageUsers.phtml",
data: { mode: "fetch" },
dataType: "json",
type: "POST"
},
update: {
url: "manageUsers.phtml",
data: { mode: "update" },
type: "POST"
},
destroy: {
url: "manageUsers.phtml",
data: { mode: "destroy" },
type: "POST"
},
create: {
url: "manageUsers.phtml",
data: { mode: "create" },
type: "POST"
},
batch: false
},
schema: {
data: "records",
total: "total",
model: {
id: "userId",
fields: {
userId: { editable: false, nullable: true },
lName: { type: "string", editable: true, validation: { required: true } },
fName: { type: "string", editable: true, validation: { required: true } },
businessUnit: { type: "string", editable: true, validation: { required: true } },
loginId: { type: "string", validation: { required: true } },
email: { type: "string", validation: { required: true } },
phone: { type: "string" },
address: { type: "string" },
city: { type: "string" },
state: { type: "string" },
zipcode: { type: "string" },
country: { type: "string" },
timezone: { type: "string" },
privs: { type: "string" }
}
}
},
pageSize: 20,
serverPaging: false,
serverFiltering: false,
serverSorting: false
},
filterable: true,
sortable: true,
pageable: true,
editable: {
mode: "popup",
template: kendo.template($("#kendo_edit_user_template").html())
},
toolbar: ["create","save","cancel"]
});
There are two point to keep in mind:
Schema.errors The field from the server response which contains server-side errors.
error is an event that will be fired if there was an error.
Basically you need to:
add to your schema an errors definition that provides access to the status sent back from the server.
Implement error event handler that, for example, restore previous value.
If your server returns the error message in a field called myError then you would have something like:
schema: {
errors: "myError",
data: "records",
total: "total",
model: {
id: "userId",
fields: {
userId: { editable: false, nullable: true },
lName: { type: "string", editable: true, validation: { required: true } },
fName: { type: "string", editable: true, validation: { required: true } },
...
or:
schema: {
errors: function(response) {
if (response.myError && response.myError !== "OK") {
return response.myError;
}
return false;
},
data: "records",
total: "total",
model: {
id: "userId",
fields: {
userId: { editable: false, nullable: true },
lName: { type: "string", editable: true, validation: { required: true } },
fName: { type: "string", editable: true, validation: { required: true } },
...
and the event would be:
dataSource: {
error : function (e) {
if (e.errors !== false) {
alert("Error: " + e.errors);
// This will cancel any change done
this.cancelChanges();
}
},
transport: {
read: {
url: "manageUsers.phtml",
data: { mode: "fetch" },
dataType: "json",
type: "POST"
},
EDIT : If what you want is to keep the popup open you should do:
dataSource: {
error : function (e) {
if (e.errors !== false) {
alert("Error: " + e.errors);
// This will keep the popup open
grid.one("dataBinding", function (e) {
e.preventDefault(); // cancel grid rebind
});
}
},
transport: {
read: {
url: "manageUsers.phtml",
data: { mode: "fetch" },
dataType: "json",
type: "POST"
},
Where I bind to databinding event just once using jQuery.one

Resources