How to Edit a row in Datatable .net core - ajax

I try to update a row in my datatable with .net core. Datatable show data and have a new/delete button that works. But when I try to edit a row, I can't get it to work.
Here is mi index.cshtml. Thanks
"ajax": {
"url": "../LoadIntervaloTrabajo",
"type": "POST",
"data": { "codigo": #Model.codigo},
"datatype": "json"
},
"columns": [
{ "data": "horario", "autowidth": true },
{ "data": "codigo", "autowidth": true },
{ "data": "descripcion", "autowidth": true },
{ "data": "horainicio", "autowidth": true },
{ "data": "duracion", "autowidth": true },
{ "data": "cortentrada", "autowidth": true },
{ "data": "cortintermedia", "autowidth": true },
{ "data": "cortsalida", "autowidth": true },
{ "render": function (data, type, row) {
return "<a href='#' class='btn btn-info' onclick=EditData('" + row.codigo + "'); >Editar</a>";
}
},
function EditData(codigo) {
var table = $("#customerDatatable").DataTable();
var r = table.rows(".selected").nodes()[0];
if ($(table.buttons(".editButton")[0].node).find("span").text() == "Cancel") {
$(r).children("td").each(function (i, it) {
if (i > 0) {
var od = table.cells(it).data()[0];
$(it).html(od);
}
});
setButtons('cancel');
} else {
$(r).children("td").each(function (i, it) {
if (i > 0) {
var h = $("<input type='text'>");
h.val(it.innerText);
$(it).html(h);
}
});
setButtons('edit');
}

I try to update a row in my datatable with .net core.
To implement updating row functionality, you can refer to the following code snippet.
Render two buttons for updating row within the last column
"columns": [
{
"data": "horario", "autowidth": true
},
{ "data": "codigo", "autowidth": true },
{ "data": "descripcion", "autowidth": true },
{ "data": "horainicio", "autowidth": true },
{ "data": "duracion", "autowidth": true },
{ "data": "cortentrada", "autowidth": true },
{ "data": "cortintermedia", "autowidth": true },
{ "data": "cortsalida", "autowidth": true },
{
"render": function (data, type, row) { return "<a href='#' class='btn btn-info' onclick = EditData(this); >Editar</a><a href='#' class='btn btn-info btn-hidden' onclick = UpdateData(this); >Updatear</a>"; }
}
]
JS function
function EditData(btnedit) {
//find current row
var $row = $(btnedit).parent().parent();
var $tds = $row.find("td").not(':nth-child(2)').not(':last');
$.each($tds, function (i, el) {
var txt = $(this).text();
$(this).html("").append("<input type='text' value=\"" + txt + "\">");
});
$(btnedit).siblings("a").removeClass("btn-hidden");
$(btnedit).addClass("btn-hidden");
}
function UpdateData(btnupdate) {
var $row = $(btnupdate).parent().parent();
var horario = $row.find("td:nth-child(1)").find("input").val();
var codigo = $row.find("td:nth-child(2)").text();
var descripcion = $row.find("td:nth-child(3)").find("input").val();
var horainicio = $row.find("td:nth-child(4)").find("input").val();
var duracion = $row.find("td:nth-child(5)").find("input").val();
var cortentrada = $row.find("td:nth-child(6)").find("input").val();
var cortintermedia = $row.find("td:nth-child(7)").find("input").val();
var cortsalida = $row.find("td:nth-child(8)").find("input").val();
var data_for_update = { "horario": horario, "codigo": codigo, "descripcion": descripcion, "horainicio": horainicio, "duracion": duracion, "cortentrada": cortentrada, "cortintermedia": cortintermedia, "cortsalida": cortsalida };
//console.log(data_for_update);
//make request to update data
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: "/{controller_name_here}/Update",
data: JSON.stringify(data_for_update),
success: function (json) {
console.log(json);
var $tds = $row.find("td").not(':nth-child(2)').not(':last');
$.each($tds, function (i, el) {
var txt = $(this).find("input").val()
$(this).html(txt);
});
$(btnupdate).siblings("a").removeClass("btn-hidden");
$(btnupdate).addClass("btn-hidden");
},
//...
});
}
CSS style
.btn-hidden{
display:none;
}
Test Result

Related

date range filter of data table is not working in laravel 8

I am applying date range filter with the help of package yajra laravel . i am trying to filter data from from_date to to_date but unfortunately it's not working please help me how can i resolve that ? I have followed this article https://www.webslesson.info/2019/07/how-to-implement-date-range-filter-in-laravel-58-datatable.html
controller
public function datatables(Request $request)
{
if(request()->ajax())
{
if(!empty($request->from_date))
{
$booking = Booking::with('users','rooms')
->whereDate('start_datetime','>=',$request->from_date)
->whereDate('end_datetime', '<=', $request->to_date)
->select(['id','user_id','room_id','start_datetime','end_datetime','points','price'])
->orderBy('created_at','DESC');
}else{
$booking = Booking::with('users','rooms')
->select(['id','user_id','room_id','start_datetime','end_datetime','points','price'])
->orderBy('created_at','DESC');
}
return Datatables::of($booking)
->addColumn('startEndDateColumn', function($row){
$time = new DateTime($row->start_datetime);
$start_date = $time->format('j-n-Y');
$time = new DateTime($row->end_datetime);
$end_date = $time->format('j-n-Y');
return $start_date . ' - ' . $end_date;
})
->addColumn('startEndTimeColumn', function($row){
$time = new DateTime($row->start_datetime);
$start_time = $time->format('h:i');
$time = new DateTime($row->end_datetime);
$end_time = $time->format('h:i');
return $start_time . ' - ' . $end_time;
})
->make(true);
}
}
datatables
load_data();
function load_data(from_date = '', to_date = '')
{
var table = $('#users-table').DataTable({
language: { search: "" },
processing: true,
serverSide: true,
ajax: "{{ route('datatables.data') }}",
data:{from_date:from_date, to_date:to_date},
"columns": [
{
"data": "startEndDateColumn",
"defaultContent": "",
"orderable": false,
},
{
"data": "startEndTimeColumn",
"defaultContent": "",
"orderable": false,
},
{ "data": "users.full_name",
"defaultContent": "",
"orderable": false,
},
{ "data": "rooms.name",
"defaultContent": "",
"orderable": false,
},
{
"data": "points",
"defaultContent": "",
"orderable": false,
},
{
"data": "price",
"defaultContent": "",
"orderable": false,
},
],
"columnDefs": [{
"targets": 'no-sort',
"orderable": false,
},
{
"targets": 0,
"render": function(data, type, row, meta) {
return data;
},
},
{
"targets": 2,
"render": function(data, type, row, meta) {
return row.rooms[0].name;
},
},
{
"targets": 3,
"render": function(data, type, row, meta) {
if(row.user_id == 0){
return "Non Member";
}else{
return row.users.full_name;
}
},
},
],
"drawCallback": function (settings) {
},
//scrollX:true,
});
};
$('#filter').click(function(){
var from_date = $('#startDate').val();
var to_date = $('#endDate').val();
if(from_date != '' && to_date != '')
{
$('#users-table').DataTable().destroy();
load_data(from_date, to_date);
}
else
{
alert('Both Date is required');
}
});
Route
Route::get('/rooms/dataTables',[RoomController::class,'datatables'])->name('datatables.data');

DataTable can not pass parameters from Ajax to ASP.NET MVC controller

I have this problem when trying to pass a string parameter from DataTable with Ajax to an ASP.NET MVC controller: the parameter is not being sent.
I tried many forms of "data:" options. Please help me, I think I'm missing something important.
When (as a test) I initialize the parameter at the beginning of the controller with ttt="CO" everything goes fine!
$('#tblVacation').DataTable({
"ajax": {
"url": '/Vacation/LoadData2',
"contentType": "application/json;charset=utf-8",
"type": 'GET',
"dataType": 'JSON',
"data" : ' { ttt: "CO" }'
"dataSrc": "",
},
"columns": [
{ "data": "vacationId", width: "5%" },
{ "data": "operatorId", width: "3%" },
{ "data": "operator", width: "10%" },
{ "data": "type", width: "3%" },
]
});
And the controller is:
[HttpGet]
public ActionResult LoadData2(string ttt)
// ttt="CO";
{
List<Vacation> data = null;
try
{
data = DB.Vacations.Include(x => x.Operator).ToList();
var result = data.Select(x => new Vacation_VM
{
VacationId = x.VacationId,
OperatorId = x.OperatorId,
Vacation_doc = x.Vacation_doc,
Operator = x.Operator.Name,
Type = x.Type,
}).Where(m => m.Type == ttt);
return new JsonResult(result);
}
catch (Exception ex)
{
ViewBag.Message = ex.Message;
}
return new JsonResult(null);
}
I also tried with
var entity = {
ttt: "CO"
}
var dataToSend = JSON.stringify(entity);
and
"data": function () {
return dataToSend;
},
but it's still not working. I will need in the future to pass multiple parameters.
Thanks a lot, I will appreciate any advice.
Replace the ajax call part with the followings:
"ajax": {
type: 'GET',
url: '/Vacation/LoadData2',
data: { ttt: "CO" },
dataType: 'JSON',
async: true,
cache: false,
},

datatable reinstallation not working in jQuery

I am trying to fill the Datatable row content dynamically using Ajax Post. But it loaded the content at first shot correctly but when I try to fill content once again it returns error Can't instantiation Datatable. .
We refereed https://datatables.net/examples/data_sources/js_array.html For datatable row content.
Can Any one please help Us.
$.ajax({
url : SITE_ROOT_DIR+"ajaxFunction.php?Exportedinvoices=1&daterange="+daterange+"&fromDate="+fromDate+"&toDate="+toDate,
type : 'post',
cache : false,
success : function(data){
var message = JSON.parse(data);
var pLen,i;
pLen=message.length;
if(pLen>0){
var carter=[];var carterarr=[];
for(i=0;i<pLen;i++)
{
var company_name=message[i]['company_name'];
var salesOrderID=message[i]['salesOrderID'];
var salesOrderDate=message[i]['salesOrderDate'];
var product_code=message[i]['product_code'];
var quantity=message[i]['quantity'];
var deliveryDate=message[i]['deliveryDate'];
var ponuber=message[i]['ponuber'];
var TermsRefFullname=message[i]['TermsRefFullname'];
var ShipMethodFullName=message[i]['ShipMethodFullName'];
var SalesRepFullName=message[i]['SalesRepFullName'];
var ItemsalesTaxRefFullname=message[i]['ItemsalesTaxRefFullname'];
var CustomerMsgRefFullName=message[i]['CustomerMsgRefFullName'];
var val=company_name+'*'+salesOrderID+'*'+salesOrderDate+'*'+product_code+'*'+quantity+'*'+deliveryDate+'*'+ponuber+'*'+TermsRefFullname+'*'+SalesRepFullName+'*'+ShipMethodFullName+'*'+ItemsalesTaxRefFullname+'*'+CustomerMsgRefFullName;
var carterarr =carterarr+val+'#';
var carter=carterarr.slice(0, -1);
}
var arlene3 = carter.split("#");
var farray=[];var Aarray=[];var myarray=[];
for(var i=0;i<arlene3.length;i++){
var arraynow=arlene3[i];
Aarray=arraynow .split("*");
myarray.push(Aarray);
}
dataSet=myarray;
$('#example1').DataTable( {
destroy: true,
data: dataSet,
columns: [
{ title: "CustomerRefFullName" },
{ title: "InvoiceRefNumber" },
{ title: "TxnDate" },
{ title: "ItemRefFullName" },
{ title: "Quantity" },
{ title: "DueDate" },
{ title: "PoNumber" },
{ title: "TermsRefFullname" },
{ title: "SalesRepFullName" },
{ title: "ShipMethodFullName" },
{ title: "ItemsalesTaxRefFullname" },
{ title: "CustomerMsgRefFullName" },
],
"ordering": false,
"searching": false,
"paging": false,
"info": false,
} );
$('.tabheading').css("display","block");
}
else
{
alert("No datas found");
}
}
});

How to reload Fuelux Tree with new data

Here i'm trying Fuelux Tree used in Ace admin Template. I have used the same code they have used.
The script code used in ace admin template:
jQuery(function($) {
var tree_data = {};
var sampleData = initiateDemoData(tree_data); //see below
$('#tree1')
.ace_tree({
dataSource: sampleData['dataSource1'],
multiSelect: true,
cacheItems: true,
'open-icon': 'ace-icon tree-minus',
'close-icon': 'ace-icon tree-plus',
'selectable': true,
'selected-icon': 'ace-icon fa fa-check',
'unselected-icon': 'ace-icon fa fa-times',
loadingHTML: '<div class="tree-loading"><i class="ace-icon fa fa-refresh fa-spin blue"></i></div>'
});
function initiateDemoData(tree_data) {
tree_data = {
"2C27D744B956": {
"text": "2C27D744B956",
"children": {
"001B179F4400": {
"text": "9991100003333",
"type": "item"
},
"9991100003333": {
"text": "9991100003333",
"type": "item"
},
"2c27d744b956": {
"text": "9991100003333",
"type": "item"
},
"002170615A04": {
"text": "9991100003333",
"type": "item"
}
},
"type": "folder"
}
};
var dataSource1 = function(options, callback) {
var $data = null
if (!("text" in options) && !("type" in options)) {
$data = tree_data; //the root tree
callback({
data: $data
});
return;
} else if ("type" in options && options.type == "folder") {
if ("children" in options)
$data = options.children || {};
else
$data = {} //no data
}
if ($data != null) //this setTimeout is only for mimicking some random delay
setTimeout(function() {
callback({
data: $data
});
}, parseInt(Math.random() * 500) + 200);
//we have used static data here
//but you can retrieve your data dynamically from a server using ajax call
//checkout examples/treeview.html and examples/treeview.js for more info
}
return {
'dataSource1': dataSource1
}
}
});
Then on a button click i'm trying to refresh the tree, with new data from ajax Get request, But when i tried, an error comes in browser such as "Uncaught TypeError: Cannot read property 'apply' of undefined ".
Following is my ajax code:
$.ajax({
type : "GET",
url : "getDevices.htm?did=" + dID,
success : function(data) {
tree_data = data; //tree_data is the data used for the treeview
$('#tree1').tree('reload');
},
error : function(data) {
console.log("failure" + data);
}
});
Please suggest a method to resolve this issue.
Thanks in advance.

My kendo Grid does not display fields by calling webserver

I need help about a kendo grid,
I call a webservice to fill a datasource of the grid. It seems to work fine, but the data are not displayed in the grid.
The webservice call returns 7 records, and in the grid there are 7 rows, but they are empty.
this is the code:
var mime_charset = "application/json; charset=utf-8";
var serverSelectReturnsJSONString = true;
var model_definition = {
id: "ID",
fields: {
customer_id: { type: "number" },
name_customer: { type: "string" },
address_customer: { type: "string" }
}
}
$(document).ready(function () {
var ds = createJSONDataSource();
$("#grid").kendoGrid({
selectable: true,
theme: "metro",
dataSource: ds,
scrollable: true,
pageable: true,
// height: 300,
toolbar: ["save", "cancel"],
columns: ["ID", "Nome", "Indirizzo"],
editable: true
});
ds.read();
});
and this is the function for filling the datasource:
function createJSONDataSource() {
var dataSource = new kendo.data.DataSource({
severFiltering: true,
serverPaging: true,
PageSize: 15,
//batch: true,
transport: {
autoSync: true,
read: {
type: "POST",
url: "WebServices/GetDataTest.asmx/getCustList",
dataType: "json",
contentType: mime_charset
}
},
schema: {
data: function (data) {
if (data) {
if (serverSelectReturnsJSONString)
return $.parseJSON(data.d);
else
return data.d;
}
},
total: function (result) {
if (!result) return 0;
var xxx = result.d;
if (xxx == null) {
return result.length || 0;
}
if (result.d) {
if (serverSelectReturnsJSONString) {
var data = $.parseJSON(result.d);
return data.length || 0;
}
else {
return result.d.TotalRecords || result.d.length || result.length || 0;
}
}
},
model: model_definition
}
});
dataSource.options.schema.parse = function (dataJ) {
var data;
data = $.parseJSON(dataJ.d);
if (data) {
$.each(data, function (i, val) {
$.each(model_definition.fields, function (j, col) {
if (col.type == "date" || col.type == "datetime") {
val[j] = toDate(val[j]);
}
})
});
var ret = { d: JSON.stringify(data) };
return ret;
}
}
dataSource.reader.parse = dataSource.options.schema.parse;
return dataSource;
}
Your columns definition is not correct, it is an array but of objects (not strings). Check documentation here. If should be something like:
columns: [
{ field: "ID" },
{ field: "Nome" },
{ field: " "Indirizzo" }
],

Resources