Data table with bootstrap using angularjs app - javascript

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' } ]
};

Related

How to get all ID's of all Checked data in all pages on Datatables

Hi i have my datatables with checkbox at the first column
i able to get the checked checkbox id but i cannot get all the data on the other page
i have this to render my datatables
var tableDelcar;
function LoadTableDelcar() {
tableDelcar = $('#tblDelcar').DataTable({
//dom: 'Brtip',
order: [[1, 'asc']],
buttons: [
'csv', 'excel', 'pdf', 'print'
],
pageLength: 10,
"ajax": {
async: false,
type: 'POST',
contentType: 'application/json',
url: 'MaintenancePage.aspx/getCarDelMaintable',
"dataSrc": "d",
dataType: 'json',
},
"columns": [
{
"d": null,
render: function (data, type, row, meta) {
return '<input type="checkbox" class="select" id="' + row.CAR_NO + '"></td>';
}, title: "Action"
},
{ "data": "CAR_NO", title: "Car No" },
{ "data": "FINDINGS", title: "FINDINGS" },
{ "data": "ActionOwner", title: "Action Owner" },
{ "data": "Auditor", title: "Status" },
{ "data": "COORDINATOR", title: "COORDINATOR" }
]
});
}
and this is my function on getting the ID's of the checked checkboxes
function DeleteCar() {
var IDs = $("#tblDelcar input:checkbox:checked").map(function () {
return $(this).attr("id");
}).get(); alert(IDs);
}
Make sure your DOM is loaded when you call your function in the other page.
you have error ?

API in javascript is returning data, but is not being saved into an array

I am trying to fetch data from an API of WordPress.
Here is my code:
column.data().unique().sort().each(function (d,j) {
var practiceArea = d.practice_area;
var jsonPacticeArea = JSON.stringify(practiceArea);
if (jsonPacticeArea !== undefined) {
var res = $.map(jsonPacticeArea.split("|"), $.trim);
for (var i = 0; i < res.length; i++) {
var str = res[i];
str = str.replace(/"/gi, '').trim();
if (arrayPracticeArea.indexOf(str) === -1) {
arrayPracticeArea.push(str);
}
}
}
});
the "column" is the variable that is getting data through an API, and as far as I do console.log(column. data().unique().sort()), that's returning complete data as you can see in the screenshot and I want to fetch data is marked in red rectangle and store those values in an array, but as soon as I try to add "each" function to fetch the data and store it in an array (in my case its arrayPracticeArea) its returning undefined values.
Can anyone please help me out? I am just not much experienced with Javascript API.
Here is my AJAX code:
var tableAttorney = $('#table_affliate_attorney').DataTable({
destroy: true,
searching: true,
bLengthChange: false,
scrollX: true,
scrollY: 440,
autoWidth: false,
"language": {
"emptyTable": "We are sorry but there are no Affiliate Attorneys within a 150 mile radius of your requested search"
},
ajax: {
type: 'get',
url: "/wp-admin/admin-ajax.php",
dataType: 'json',
cache: false,
data: {
'action': 'get_attorney_ajax',
'center_lat': center_lat,
'center_long': center_long,
'state': state,
'city': city,
'zip': zip
}
},
columns: [
{"data": "title"},
{"data": "city"},
{"data": "state"},
{"data": "zip"},
{"data": "distance"},
{
"data": "phone",
className: 'datatablePhone',
render: function (data) {
return '' + data + '';
}
},
{
"data": "email",
className: 'px190EM',
render: function (data) {
return '' + data + '';
}
},
{
className: 'js-practice-area',
"data": "practice_area"
},
{
"targets": -1,
"data": 'email',
render: function (data) {
return "<a class='contact-lawyer' href='#' data-toggle='modal' data-target='#exampleModal' data-whatever='#mdo' data-email='"+data+"'>Contact</a>";
}
},
],
columnDefs: [
{"width": "150px", "targets": [0]},
{"width": "130px", "targets": [5]}
],
So I am trying to fetch data from columns->data that has value practice_area

How Link to Route in JS

I'm using Laravel 8.
I wish I could link the field "nama" to show the categories in detail (the examples in red arrows).
JS for table
#push('scripts')
<script>
$(function() {
$('#kategoris-table').DataTable({
processing: true,
serverSide: true,
ajax: 'kategori/json',
columns: [
{ data: 'id', name: 'id' },
{ data: 'nama', name: 'nama' },
{ data: 'created_at', name: 'created_at' },
{ data: 'updated_at', name: 'updated_at' }
]
});
});
</script>
#endpush
I also wish to know how to set the date format because when I looked at that field it feels so messed up. Here's my view table.
Try this
$(function() {
$('#kategoris-table').DataTable({
processing: true,
serverSide: true,
ajax: 'kategori/json',
columns: [
{ data: 'id', name: 'id' },
{ data: 'nama', name: 'nama',
fnCreatedCell: function (nTd, sData, oData, iRow, iCol) {
$(nTd).html("<a href='/category_details/"+oData.id+"'>"+oData.nama+"</a>");
}
},
{ data: 'created_at', name: 'created_at' },
{ data: 'updated_at', name: 'updated_at' }
]
});
});
You can read here more about it - https://datatables.net/reference/option/columns.createdCell

Datatables: You clicked on undefined's row

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' );

datatables server side processing(load on demand)

i am trying to do a server side processing which is load on demand , i am using mvc to develop my application
the following is my code on the datatables js class,
var initTrackingTable = function () {
var table = $('#tableCategoryList');
var daterange = $("#daterangepicker").val();
val_CategoryName = $("#SearchTextBox").val();
//val_Daterange = $("#trackingForm").find("[name='daterangepicker']").val();
settingsInitEmpty = {
ajax: ({
url: "/Product/LoadCategoryData?category=" + val_CategoryName,
type: "POST",
datatype: "json"
}),
// ### FOR SERVERSIDE LODING
processing: true,
serverSide: true,
filter: false,
orderMulti: false,
columns: [
{ data: "category_id", name: "category_id", autoWidth: true },
{ data: "category_name", name: "category_name", autoWidth: true, render: function (data, type, row) { return '<span class="">' + data + '</span>' } },
{ data: "sort_order", name: "sort_order", autoWidth: true },
],
initComplete: function (settings, json) {
$("#tableCategoryList").parent().addClass("tableTransactionGridWrapper")
}
};
categoryTable = table.DataTable(settingsInitEmpty);
}
on the category_name there, i wish to put the hyperlink, however the hyperlink i intend to put the category_id as a query string parameter so i am able to edit the category. may i ask is this achievable? if yes, how the code suppose to be?

Categories