Datatables: You clicked on undefined's row - javascript

I have this definition of a Datatable defined on a Thymeleaf template of a SpringBoot application, using Datatables:
<script th:inline="javascript">
/*<![CDATA[*/
$(document).ready(function() {
var table = $('#workerEventTable').DataTable( {
order: [[ 0, "desc" ]],
select: true,
bLengthChange: false,
stateSave: true,
pageLength: 20,
ajax: 'http://127.0.0.1:1234/acerinox/api/deviceevent/datatableList',
"columns": [
{ data: 'id' },
{ data: 'deviceId' },
{ data: 'companyName' },
{ data: 'description' },
{ data: 'battery' },
{ data: 'dateTime' },
{ data: 'signal' },
{ data: 'data' },
{ data: 'alarm' }
]
});
setInterval( function () {
table.ajax.reload( null, false ); // user paging is not reset on reload
}, 1000 );
table.on('select.dt deselect.dt', function() {
localStorage.setItem( 'DataTables_selected', table.rows( { selected: true }).toArray() )
})
$('#workerEventTable tbody').on('click', 'tr', function () {
var data = table.row( this ).data();
alert( 'You clicked on '+data[0]+'\'s row' );
} );
} );
/*]]>*/
</script>
Expecting that when I click on a row I should see the ID, but instead I see this error message: Datatables: You clicked on undefined's row

You are using object based data because you defined columns.data. To access the id try this:
alert( 'You clicked on '+data.id+'\'s row' );

Related

how to add a href route with parameter in datatable

here is i have a datatable based table i have fetched a data from database and displayed using datatable but in this datatable i went to redirect to show for each row of datatable so how to add a route for show with parameter 1d for each row thanks and waiting a positive response!
here is my code
<script>
$(function() {
$("#start_date").datepicker({
"dateFormat": "yy-mm-dd"
});
$("#end_date").datepicker({
"dateFormat": "yy-mm-dd"
});
});
// Fetch records
function fetch(start_date, end_date,zone_id,status_id,sector_id) {
$.ajax({
url: "{{ route('ProjectFilterdate/records') }}",
type: "GEt",
data: {
start_date: start_date,
end_date: end_date,
zone_id:zone_id,
status_id:status_id,
sector_id:sector_id
},
dataType: "json",
success: function(data) {
// Datatables
var i = 1;
$('#records').DataTable({
"data": data.ptojects,
// buttons
"dom": "<'row'<'col-sm-12 col-md-4'l><'col-sm-12 col-md-4'B><'col-sm-12 col-md-4'f>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>",
"buttons": [
'copy','excel', 'pdf', 'print'
],
// responsive
"responsive": true,
"columns": [{
"data": "id",
"render": function(data, type, row, meta) {
return i++;
}
},
{
"data": "code"
},
{
"data": "name"
},
{
"data": "proposal_date"
},
{
"data": "proposal_value"
},
{
"data": "contractor"
},
{
"data": "subcontractor"
},
{
render: function ( data, type, row) {
return 'test';
}
},
]
});
}
});
}
i am trying to make an a href route but i don't know how to add an id parameter
here is the link i am trying
{
render: function ( data, type, row) {
return 'test';
}
the place of 1 must be replaced by id for each row
This is how i did t :
return DataTables::of($data)->addIndexColumn()
->addColumn('project', function ($test) {
return $test->project->title;
})
->addColumn('action', function ($test) {
$result = $test->active ? 'btn-success' : 'btn-danger';
return '<a href="' . route('projectDetail', [
'id' => $test->id
]) . '">detail </a>
';
})
->rawColumns([
'action'
])
->make(true);
}

Row-Reorder Function Calling Ajax Multiple Time to Save in Database

I have datatable Like this
oInnerTable = $("#url_table_" + rotator_id).DataTable({
"processing": true,
"serverSide": true,
rowReorder: {
dataSrc: [1]
},
"ajax":{
url :"actions/data_url_response.php",
type: "post",
data: function ( d ) {
var url_status = $('.url_status').val();
d.rotator_id = rotator_id;
d.url_status = url_status;
}
},
autoWidth: false,
columnDefs: [
{ "visible": false, "targets": 0 },
{ orderable: true, className: 'reorder', targets: 0 },
{
"targets":[0, 7],
"orderable":false,
},
{
targets: 0,
render: function (data, type, row) {
return '<div class="form-check"><input type="checkbox" class="form-check-input position-static select_ids" value="'+row[0]+'"></div>';
}
},
],
dom: '<"datatable-scroll"t><"datatable-footer"ip>',
language: {
search: '<span>Filter:</span> _INPUT_',
searchPlaceholder: 'Type to search...',
lengthMenu: '<span>Show:</span> _MENU_',
paginate: { 'first': 'First', 'last': 'Last', 'next': $('html').attr('dir') == 'rtl' ? '←' : '→', 'previous': $('html').attr('dir') == 'rtl' ? '→' : '←' }
}
});
And Update function is like below
var positionArray = [];
oInnerTable.on( 'row-reorder', function ( e, diff, edit ) {
for ( var i=0, ien=diff.length ; i<ien ; i++ ) {
var rowData = oInnerTable.row( diff[i].node ).data();
positionArray.push({
myid:rowData[0],
mypositiion: diff[i].newData
});
}
if (positionArray.length>0) {
$.post("/link-to-script.php", {
positionArray: positionArray
}, function(data, status) {
positionArray = [];
})
} ;
} );
Since I have three rows in table, everytime when I change position, its calling ajax three time and sometime its even more time, Its not possible that its fire only one time and I can send position data to server with single ajax call?
Thanks!

how to check status in if condition

I want to check the status which is come from a model in the form 0 and 1 but I have to show 0 as a enable and 1 as a disable but don't know how to use if below code
#push('scripts')
<script type="text/javascript">
$(document).ready(function() {
$('#role-table').DataTable({
serverSide: true,
processing: true,
responsive: true,
ajax: '{{ route("admin.role.getRoleList") }}',
columns: [
{ data: 'id', name: 'id',className:'text-center' },
{ data: 'name', name: 'name' },
{ data: 'status', name: 'status' },
{ data: 'action', name: 'action', classrole: 'text-center', orderable: false }
],
stateSave: true
});
});
</script>
#endpush
For formatting your status column, use this:
{
data: 'status',
name: 'status',
render: function ( data, type, row ) {
return data?$'<span> disable </span>':'<span> enable </span>';
}
}
Note that you have the power to use HTML tags for formatting your data columns.
For more information visit DataTable Renders
Write your yajra datatables query like this:
return datatables()->of($model)
->editColumn('status', function ($query) {
if($query->status == 0)
{
return 'enable';
}
else
{
return 'disable';
}
})
->escapeColumns([])
->make(true);

Updating Div with Total Records Outside of table

I’m working with datatables and trying to figure out what I’m doing wrong. I am trying to display the total number of rows when the table hits the draw event on the table. Right now with the code, I’m showing below I am not getting any console errors. The element where the number is supposed to be updated is correct. I am just not getting it to render with the correct count.
("use strict");
const renderStatusCell = (data, type, full, meta) => {
const status = {
0: { title: "Inactive" },
1: { title: "Active" }
};
if (typeof status[data] === "undefined") {
return data;
}
return status[data].title;
};
var table = $('[data-table="users.index"]');
// begin first table
table.DataTable({
// Order settings
order: [[1, "desc"]],
ajax: "/titles",
columns: [
{ data: "id", title: "User ID" },
{ data: "name", title: "Name" },
{ data: "slug", title: "Slug" },
{ data: "introduced_at", title: "Date Introduced" },
{ data: "is_active", title: "Status", render: renderStatusCell },
{
data: "action",
title: "Actions",
orderable: false,
responsivePriority: -1
}
]
});
var updateTotal = function() {
table.on("draw", function() {
$("#kt_subheader_total").html(table.fnSettings().fnRecordsTotal());
});
};
I expected when the table was rendered to update the dom with the correct number of rows however the div does not get updated.
I don't understand your problem, but I think you need something like that.
table
.row($(this).parents('tr'))
.remove()
.draw();
or
table.ajax.reload();
I believe you need to wait until the HTML loads before running all your javascript code. Also, if you are storing the total, you not make it a function but rather just store the value.
'use strict';
// this will make sure all the HTML loads before the JavaScript runs.
$(function() {
var table = $('[data-table="users.index"]');
var updateTotal = null; // store in a variable
const renderStatusCell = (data, type, full, meta) => {
const status = {
0: { title: "Inactive" },
1: { title: "Active" }
};
if (typeof status[data] === "undefined")
return data;
return status[data].title;
};
// begin first table
table.DataTable({
// Order settings
order: [[1, "desc"]],
ajax: "/titles",
columns: [
{ data: "id", title: "User ID" },
{ data: "name", title: "Name" },
{ data: "slug", title: "Slug" },
{ data: "introduced_at", title: "Date Introduced" },
{ data: "is_active", title: "Status", render: renderStatusCell },
{
data: "action",
title: "Actions",
orderable: false,
responsivePriority: -1
}
]
});
table.on("draw", function() {
updateTotal = table.fnSettings().fnRecordsTotal();
$("#kt_subheader_total").html(table.fnSettings().fnRecordsTotal());
});
});

Data table with bootstrap using angularjs app

I am using jquery data table with bootstrap and facing one little issue which i don't understand.
Here is my code
$scope.LoadTypesView = function() {
$http({
method : 'POST',
url : "servierapi.php",
data : SessionId, // pass in data as strings
headers : { 'Content-Type': 'application/json' } // set the headers so angular passing info as form data (not request payload)
})
.success(function(data) {
if(data.aaData.status=="success") // i get two message error and success and work well
{
$scope.Type = data.aaData.response;
var oTable = $('#typess').dataTable( {
"sDom": "<'row-fluid'<'span6'T><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
"oTableTools": {
"aButtons": [
"copy",
"print",
{
"sExtends": "collection",
"sButtonText": 'Save <span class="caret" />',
"aButtons": [ "csv", "xls", "pdf" ]
}
]
},
"bProcessing": true,
"sAjaxSource": '$scope.Type'
} );
$('#types').modal('show');
}
});
};
Here is my json array which i receive from server and assign to $scope.Type variable
{"aaData":{"status":"success","response":[{"UserTypeId":"1","TypeName":"Admin","CreatedOn":"2014-02-24 00:00:00","AssignedUsers":[{"UserId":"7","UserTypeId":"1","UserRegionId":"1","UserDepartmentId":"1","UserDesignationId":"1","CNIC":"xxxxxxxx","FirstName":"Hafiz","LastName":"Haseeb","Dob":"January 1,1970","PhotoName":"","PhotoPath":"","Email":"xxxxxx","EducationLevel":"","MartialStatus":"","City":"","State":"","Country":"","MobileNumber":"","EmergencyNumber":"","AddressOne":"","AddressTwo":"","CreatedOn":"0000-00-00 00:00:00","Salary":""}]}]}}
I also check JSON array on this link http://jsonformatter.curiousconcept.com/ and json array is valid.
why i am getting this error
Data Tables warning: JSON data from server could not be parsed. This is caused by a JSON formatting error.?
You are using "sAjaxSource": '$scope.TypeId' as a string , this is variable you can use this like sample code and some data functions and its parameters
"sAjaxSource": $scope.TypeId,
"sAjaxDataProp": "aaData",
'fnServerParams' : function (aoData) {
aoData.push({"name":"SessionId", "value":Session_Id});
}
I hope this will help to solve your problem
this.Display_error = false; this.sign_report.value.status = 0;
this.signOptions = {pagingType: 'full_numbers', paging: true, ordering: false, dom: 'Bflrtip', pageLength: 10,
processing: true, serverSide: true, buttons: ['copyHtml5', {extend: 'excelHtml5', text: 'To Excel', title: this.in_header},
{extend: 'pdfHtml5', text: 'To Pdf', title: this.in_header},
{extend: 'print', text: 'Direct Print', title: this.in_header}],
ajax: (dataTablesParameters: any, callback) => {
this.http.post<DataTablesResponse>(this.db.CheckIf_url, dataTablesParameters, {}).subscribe(resp => {
console.log(resp.data); this.signinoutmodel = resp.data;
callback({
draw: resp.draw,
recordsTotal: resp.recordsTotal,
recordsFiltered: resp.recordsFiltered,
data: resp.data
});
});
},
fnServerParams: function(dt) {
dt.signedfrom = fd.signedfrom;
dt.signedtill = fd.signedtill;
dt.status = fd.status;
dt.sort_event = fd.sort_event;
dt.signed_in_at = fd.signed_in_at;
dt.signed_out_at = fd.signed_out_at;
dt.sort_category = fd.sort_category;
},
columns: [{ data: 'tblid' }, { data: 'staff_id' }, { data: 'fullname' }, { data: 'event_name' },
{ data: 'sign_in' }, { data: 'sing_out'}, { data: 'date_signed' } ]
};

Categories