jquery server-side datatable not wroking properly - javascript

I added the server side jQuery data-table, Data from back-end coming correctly for all pagination, sorting etc. and also bind the data first time, but second time not replacing the content of data-table with new data.
Here is my JQuery code:
var table = $('#example').DataTable({
"processing": true,
"serverSide": true,
"ajax":
{
"url": "View_account.aspx/GetData",
"contentType": "application/json",
"type": "GET",
"dataType": "JSON",
"data": function (d) {
return d;
},
"dataSrc": function (json) {
json.draw = json.d.draw;
json.recordsTotal = json.d.recordsTotal;
json.recordsFiltered = json.d.recordsFiltered;
json.data = json.d.data;
var return_data = json;
return return_data.data;
}
},
"columns": [
{
"data": "tblRow",
"render": function (data, type, row) {
console.log(data)
return data;
}
},
{ data: "cust_name" },
{ data: "status" },
{
data: "account_id",
"render": function (data, type, row) {
console.log(data)
return '<td><i class="fa fa-pencil edt_icn" aria-hidden="true"></i></td>';
}
},
{
data: "account_id",
"render": function (data, type, row) {
console.log(data)
return '<i class="fa fa-trash delet_wrpr delt_icn" aria-hidden="true"></i>';
}
},
{
data: ".account_id",
"render": function (data, type, row) {
console.log(data)
return "<input value='" + row.account_id + "' id='record" + row.account_id + "' name='record" + row.account_id + "' type='checkbox'>";
}
}
]
});
Please Help. Thank you in advance.

Try with "columnDefs"(datatables example) prop instead "columns" like:
var table = $('#example').DataTable({
"processing": true,
"serverSide": true,
"ajax":
{
"url": "View_account.aspx/GetData",
"contentType": "application/json",
"type": "GET",
"dataType": "JSON",
"data": function (d) {
return d;
},
"dataSrc": function (json) {
json.draw = json.d.draw;
json.recordsTotal = json.d.recordsTotal;
json.recordsFiltered = json.d.recordsFiltered;
json.data = json.d.data;
var return_data = json;
return return_data.data;
}
},
// HERE CHANGE
"columnDefs": [
{
// HERE CHANGE ( COLUMN INDEX)
"targets": 0,
"render": function (data, type, row) {
console.log(data)
return data;
}
},
{
"targets": 3,
"render": function (data, type, row) {
console.log(data)
return '<td><i class="fa fa-pencil edt_icn" aria-hidden="true"></i></td>';
}
},
{
"targets": 4,
"render": function (data, type, row) {
console.log(data)
return '<i class="fa fa-trash delet_wrpr delt_icn" aria-hidden="true"></i>';
}
},
{
"targets": 5,
"render": function (data, type, row) {
console.log(data)
return "<input value='" + row.account_id + "' id='record" + row.account_id + "' name='record" + row.account_id + "' type='checkbox'>";
}
}
]
});

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

Issue with Datatable and JSON calculation

I am using datatable, loading data from ajax and preforming operation with javacript.
var table = $('#example').DataTable({
"ajax": {
"url": apiurl,
"type": 'GET',
"datatype": 'json'
},
// data: dataSet,
columns: [
{ title: "Item Key", data: "itemKey" },
{ title: "Description", data: "description" },
{ title: "Pounds", data: "pound" },
{
title: "Current Cost", data: function (data, type, row) {
return '<input type="number" class ="price-input" value="' + data.cost + '" style="background-color:lightgoldenrodyellow;">';
}
},
{ title: "Current Cost", data: "cost" },
{ title: "Unit", data: "unit" },
{
title: "Quantity", data: "quantity"
},
{
title: "Total", data: function (data, type, row) {
return data.cost * data.quantity;
}
},
{
title: "New Total", "data": "total",
"render": function (data, type, row) {
return "$" + data;
}
}
],
});
function calcTotal(q, p) {
var t = 0.00;
t = parseInt(q) * parseFloat(p);
return t.toFixed(2);
}
var table = $('#example').DataTable();
$.each(table, function (i, r) {
r.total = calcTotal(r.qty, r.price);
});
$("#example").on("change", ".price-input", function (event) {
var row = $(this).closest("tr");
var qty = table.cell($("td", row).eq(6)).data();
var price = $(this).val();
var total = table.cell($("td", row).eq(8).get(0));
total.data(calcTotal(qty, price)).draw();
});
'''
My problem is in the last column, when the datatable loads, value appear as undefined, when I change the value in textbox I am getting the right result and number How Can I able to see right number when Datatable loads? Please guide me

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 to call Function in Jquery Datatable

I have these lines of code. I want to add function to some row. When clicked it runs another function. But It not recognise function declaration.How can I call function when clicked some row? and how can i send parameters to that function associated with that row.
$(document).ready(function() {
var restVul = function() {
alert("tik");
}
$.ajax({
url: "https://localhost:450/rest/products?pageNumber=1&pageCount=80",
type: "POST",
dataType: "json",
headers: {
'Content-Type': 'application/json'
},
traditional: true,
contentType: "application/json; charset=utf-8",
processData: false,
data: JSON.stringify(hostAddresses),
success: function(response) {
console.log(response);
for (var i = 0; i < response.length; i++) {
var trHTML = '';
for (var j = 0; j < response[i].Products.length; j++) {
trHTML += '<tr class="clickable-row" data-href="index.html"><td>' + response[i].IP + '</td><td onclick="function () {alert(); }">' + response[i].Products[j].Product + '</td><td>' + response[i].Products[j].CVECount + '</td></tr>';
}
$('#ProductsTableBody').append(trHTML);
}
$('.js-exportable').DataTable({
dom: 'Bfrtip',
responsive: true,
buttons: [
'copy', 'csv', 'excel', 'pdf', 'print'
]
});
},
error: function(xhr) {
console.log("Hata Oluştu...");
}
})
Use following code in the row
columns: [
{"data": "xxx", "width": "10%","visible": false, "render": function (data, type, row, meta) { } },
]
Use following code inside the function to make a clickable link on column
if (type === 'display') {
return $('<a>')
.attr('href', ' ')
.text(data)
.wrap('<div></div>')
.parent()
.html();
} else {
return data;
}

dataTables Change Data for ajax call

I'm using the following function to load a DataTables table with data from the server. I would like to reload the table with different parameters on a click event only i cant work out how to do this. If i call reload it just reloads with the original parameters if i reinitialise the whole table it throws an error as the table already exists.
I have been looking into fnServerParams but cant work out if it would help or not.
If anyone can point me in the correct direction that would be great.
function LoadRiskProfileModalTable(userId, teamId, riskProfileClass) {
var params = {
userId: userId,
teamId: teamId,
riskProfileClass: riskProfileClass
};
var data = JSON.stringify(params);
//if (!$.fn.DataTable.isDataTable("#riskProfileTable")) {
var table = $("#riskProfileTable").DataTable({
"bProcessing": true,
"sAjaxSource": "WFMHome.aspx/GetRiskProfileDrillThroughDatatable",
"fnServerData": function (sSource, aoData, fnCallback) {
//aoData.push(JSON.stringify(params));
$.ajax({
"dataType": 'json',
"contentType": "application/json; charset=utf-8",
"type": "POST",
"url": sSource,
"data": data,
"success": function (msg) {
var json = jQuery.parseJSON(msg.d);
fnCallback(json);
$("#riskProfileTable").show("fast", function () { $('#riskProfileTableLoading').hide("fast") });
},
error: function (xhr, textStatus, error) {
if (typeof console == "object") {
appendAlert("errorAlertPlaceholder", xhr.responseText, 1, "danger");
console.log(xhr.status + "," + xhr.responseText + "," + textStatus + "," + error);
}
}
});
},
"columns": [
{ "data": "CaseHandler" },
{ "data": "caseAreaText" },
{ "data": "RiskProfileText" },
{ "data": "PassChecks" },
{ "data": "F1Checks" },
{ "data": "F2Checks" },
{ "data": "F3Checks" },
{ "data": "CurrentChecks" }
]
});
//}
//else {
// $('#riskProfileTable').DataTable().ajax.reload();
// }
};
If you just want to replace the data you have now by the data coming from the server, try to replace the success method by:
"success": function (msg) {
var json = jQuery.parseJSON(msg.d); //I assume it's the data set
var table = $("#riskProfileTable").DataTable();
table.rows.clear(); //clear the current data
table.rows.add(json).draw();
$("#riskProfileTable").show("fast", function () { $('#riskProfileTableLoading').hide("fast") });
},

Categories