get the ID of specific row in JQuery datatable - javascript

I have JQuery table like following image
I want to alert the ProductID once I click V link text in Action column
<table id="productTable">
<thead>
<tr>
<th>ProductID</th>
<th>TitleEN</th>
<th>TypeEN</th>
<th>ModifiedDate</th>
<th>Actions</th>
</tr>
</thead>
</table>
#* Load datatable css *#
<link href="//cdn.datatables.net/1.10.9/css/jquery.dataTables.min.css" rel="stylesheet" />
#section Scripts{
#* Load DataTable js here *#
<script src="//cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$("#productTable").DataTable({
"info": false,
"processing": true,
"serverSide": true,
"filter": false,
"orderMulti": false,
"ajax": {
"url": "/Home/LoadProductData",
"type": "POST",
"datatype": "json"
},
"columns": [
{ "data": "Product_ID", "name": "Product_ID", "autoWidth": true },
{ "data": "Product_Title_EN", "name": "Product_Title_EN", "autoWidth": true },
{ "data": "Product_Type_EN", "name": "Product_Type_EN", "autoWidth": true },
{ "data": "ModifiedDate", "name": "ModifiedDate", "autoWidth": true },
{
data: null,
className: "center",
defaultContent: ' V '
}
]
});
});
$('#editor_view').on('click', 'a.editor_view', function (e) {
alert($("data-Product_ID").val());
});
</script>
}
currently I alerted its like this
alert($("data-Product_ID").val());
but it cant get the ID of that, hw can I do this ?
this is the html for table row
<tr class="even" role="row">
<td class="sorting_1">02</td>
<td>Current Accounts</td>
<td>Assets</td>
<td></td>
<td class=" center">
<a class="editor_view" href="#"> V </a>
</td>

Change your script to
$("#productTable").on('click', '.editor_view', function() {
var ID = $(this).closest('tr').find('td').eq(0).text();
alert(ID);
});
Note that your dynamically generating the table rows so you need event delegation attached to an element that exists in the DOM when the view is first generated (i.e the element with id="productTable").

Below is my Data table.
table_low_stocks.dataTable({
"bLengthChange": true,
"processing": false,
// "serverSide": true,
"bPaginate": false,
"bInfo": false,
"iDisplayLength" : 5,
"bSort" : true,
"ajax": {
'type': 'POST',
'url': "<?=action('AdvertiserproductsController#postLowstockproducts')?>"
},
"columns": [
/* {"data": "sr_no"}, */
{"data": "product_name"},
{"data": "inventory"},
{"data": "update"}
] // set first column as a default sort by asc
});
This is how i am rendering the HTML (Datatable from Controller )
return Datatables::of($data)
->add_column('action','<a data-productid="{{$sr_no}}" class="label label-sm label-messages-btn update-product"> <i class="fa fa-pencil-square-o"></i> Update Stock </a>')
->make(true);
If you have seen above i have given data-productid="{{$sr_no}}" to a tag
so ultimately that is what you have to give anyhow,.
Now from the jquery part.what have done is .
$(document).on("click",".update-product", function(e){
e.preventDefault();
var getProductId = $(this).data("productid");
alert(getProductId);
});
and i got the product Id :-)
to give data attribute do like
data-productid="{{$sr_no}}"
and to get the data attribute u have to use
$(selector).data("productid");
Hope this is helpfull to you.

$('#editor_view').on('click', 'a.editor_view', function (e) {
alert($("data-Product_ID").val());
});
Here you have used "editor_view" as ID and I can view it is set as a class, so it will not work. It should be like
$('.editor_view').on('click', 'a.editor_view', function (e) {
alert($("data-Product_ID").val());
});

Related

Edit DataTables source data, using form inside pop-up window

I have a datatable that fetches records from database with ajax. I want to add the edit tooltip like jquery-datatables-editor extension to datatables but for free. Is there any plugin to do this? if not, can any one help me to do this manually?
This is my JavaScript code:
$('#table_id').DataTable({
"serverSide": true,
"processing": true,
"ajax": function (data, callback, settings) {
$.ajax({
url: '/some url',
type: 'GET',
data: data,
success: function (data) {
console.log(data)
}
});
},
"columns": [{
"title": "edit",
"data": null,
"className": "center",
"defaultContent": ' Edit / Delete '
}, {
"title": "name",
"data": "name"
}, {
"title": "id",
"data": "id"
},
]
});
Since your question (and posted code sample) are mostly concerned with front-end part of editable rows feature I will focus on that primarily as backend logic is pretty much straightforward (update/insert data into storage upon AJAX-request receipt).
In order to implement that feature following logic I may suggest:
append (by means of createdRow option) some anchor (row().index() or source object id property, etc) to your source data within some <tr> attribute (e.g. rowindex), so you will know later on which entry to modify server-side:
$('table').DataTable({
...
createdRow: (tr, _, rowIndex) => $(tr).attr('rowindex', rowIndex)
})
append some anchor attribute (e.g. data-src) to your editor pop-up (I'll use bootstrap-4 modal for that purpose) <input> nodes to link those input fields to corresponding source object properties:
<div><label>PropertyX:</label><input data-src="propertyX"></input></div>
upon clicking edit button, grab corresponding row data, populate editor pop-up <input> fields with that data, pass anchor to edited row (rowindex attribute value) over to pop-up attribute:
//for table id 'example' handle clicking
//edit button having class 'edit'
$('#example').on('click', '.edit', function () {
//get clicked row invoking row() API method
//against DataTables object assigned to dataTable
const rowClicked = dataTable.row($(this).closest('tr'));
//populate edit form with row data by corresponding
//rowClicked property based on 'data-src' attribute
$.each($('#editform input'), function () {
$(this).val(rowClicked.data()[$(this).attr('data-src')]);
});
//set modal attribute rowindex to corresponding row index
$('#editform').attr('rowindex', rowClicked.index());
//open up edit form modal
$('#editform').modal('toggle');
});
upon completing row data editing, store <input> values into object:
const modifiedData = {};
$.each($('#editform input'), function(){
Object.assign(modifiedData, {[$(this).attr('data-src')]:$(this).val()});
});
POST data (along with corresponding rowindex) to the server and reload (ajax.reload()) up-to-date datatable upon success:
$.ajax({
url: '/editrow',
method: 'POST',
data: {id: $('#editform').attr('rowindex'), ...modifiedData},
success: () => {
$('#editform').modal('hide');
dataTable.ajax.reload();
}
});
Complete live demo of that method you might examine in your browser's DevTools by the following link with some bonus in form of row delete button.
Both HTML and jQuery code sample might look as follows (not executable as there's no supporting backend):
$(document).ready(() => {
//data table initialization
const dataTable = $('#example').DataTable({
ajax: {
url: '/getdata',
type: 'GET',
dataSrc: ''
},
dom: 't',
//use <tr> attribute 'rowindex' to anchor to source data row index
createdRow: (tr, _, rowIndex) => $(tr).attr('rowindex', rowIndex),
columns: [
{data: 'name', title: 'Name'},
//append 'Edit'/'Delete' buttons to the rightmost edge of the cell
{data: 'title', title: 'Title', render: (cellData, _, __, meta) => cellData+'<i class="delete fa fa-trash"></i><i class="edit fa fa-pencil"></i></button>'}
],
});
//delete button handler
$('#example').on('click', '.delete', function() {
//extract the index of the row to delete
//from 'rowindex' attribute
const rowIndex = $(this)
.closest('tr')
.attr('rowindex');
//do AJAX-call to the backend
$.ajax({
url: '/deleterow',
method: 'DELETE',
data: {id: rowIndex},
//re-draw datatable with up to date data
success: () => dataTable.ajax.reload()
});
});
//edit button handler (open up edit form modal)
$('#example').on('click', '.edit', function(){
//get clicked row
const rowClicked = dataTable.row($(this).closest('tr'));
//populate edit form with row data by corresponding
//rowClicked property based on 'data-src' attribute
$.each($('#editform input'), function(){
$(this).val(rowClicked.data()[$(this).attr('data-src')]);
});
//set modal attribute rowindex to corresponding row index
$('#editform').attr('rowindex', rowClicked.index());
//open up edit form modal
$('#editform').modal('toggle');
});
//submit edits handler
$('#editform').on('click', '#submitedits', function(){
//grab modified data into object
const modifiedData = {};
$.each($('#editform input'), function(){
Object.assign(modifiedData, {[$(this).attr('data-src')]:$(this).val()});
});
//send modified data to the backend
$.ajax({
url: '/editrow',
method: 'POST',
data: {id: $('#editform').attr('rowindex'), ...modifiedData},
success: () => {
//close the modal
$('#editform').modal('hide');
//re-draw datatable
dataTable.ajax.reload();
}
});
});
});
<!doctype html>
<html>
<head>
<script type="application/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="application/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="https://use.fontawesome.com/937a319e2f.js"></script>
<script type="application/javascript" src="/main.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="/main.css">
</head>
<body>
<!-- Table -->
<table id="example"></table>
<!-- Modal -->
<div class="modal fade" id="editform" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Row details</h5>
</div>
<div class="modal-body">
<form>
<div class="form-group"><label>Name:</label><input data-src="name" class="form-control"></input></div>
<div class="form-group"><label>Title:</label><input data-src="title" class="form-control"></input></div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline-dark" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-outline-dark" id="submitedits">Save changes</button>
</div>
</div>
</div>
</div>
</body>
</html>
If you mean JQUERY DATATABLE then you can insert input fields (that would still retain the cell data) for every column within your table row as you desire and set the borders of the input field to not display, with css.
EXAMPLE TABLE
<style>
.no-input-border {
border: 'none' !important; background: 'none' !important;
}
</style>
<table id="dynamic_table">
<thead>
<tr>
<th>Name</th>
<th>State</th>
<th>Address</th>
<th>Active</th>
<th>Action</th> <!-- This column would hold your buttons -->
</tr>
</thead>
<tbody>
</tbody>
</table>
EXAMPLE DATATABLE INITIALIZATION
var table = $('#dynamic_table').DataTable({
"order":[[ 0, 'asc' ]], // order by first column
"processing": true,
'paging': true,
'searching': true,
'retrieve': true,
'serverSide': true,
'ajax': {
'url': "your-ajax-url",
'type': 'POST'
},
'columns': [ //every **name:** value must be present in your json
{ data: null, name: 'name'},
{ data: null, name: 'state' },
{ data: null, name: 'address' },
{ data: null, name: 'active' },
{ data: null, name: 'id' } // column that holds your buttons
],
"columnDefs": [
{
"targets": 0, // column that inserts an input field
"data": 'name',
"orderable": false,
"createdCell": function (td, cellData, rowData, row, col){
return '<input type="text" class="no-input-border" name="name" value="'+cellData+'" />'
}
},
{
"targets": 1, // column that inserts an input field
"data": 'state',
"orderable": false,
"createdCell": function (td, cellData, rowData, row, col){
return '<input type="text" class="no-input-border" name="state" value="'+cellData+'" />'
}
},
{
"targets": 2, // column that inserts an input field
"data": 'address',
"orderable": false,
"createdCell": function (td, cellData, rowData, row, col){
return '<input type="text" class="no-input-border" name="state" value="'+cellData+'" />'
}
},
{
"targets": 3, // column that inserts an input field
"data": 'active',
"orderable": false,
"createdCell": function (td, cellData, rowData, row, col){
return '<input type="text" class="no-input-border" name="active" value="'+cellData+'" />'
}
},
{
"targets": 4, // column that holds your buttons
"data": 'id',
"orderable": false,
"createdCell": function (td, cellData, rowData, row, col){
return '<button class="edit_row">Edit<button>'
}
}
],
'responsive': true,
'initComplete': function(settings, json) {
//Run a function when table first initializes
},
'drawCallback': function( settings ) {
//Run a function anytime table reloads when paginating
}
});
EXAMPLE DATATABLE ROW EDIT FUNCTION
$('#dynamic_table tbody').on('click', '.edit_row', function () {
var row = table.row( $(this).parents('tr') ); // row that was clicked
var d = row.data(); // data of the row button that was clicked .eg. console.log(d.name)
var index = row.index();
var json = { // json to be sent
id: d.id,
name: table.cell(index,0).nodes().to$().find('input').val(),
state: table.cell(index,1).nodes().to$().find('input').val(),
address: table.cell(index,2).nodes().to$().find('input').val(),
active: table.cell(index,3).nodes().to$().find('input').val()
}
/*Your Ajax Function Here*/
});
RELOAD DATATABLE FUNCTION
table.ajax.reload( function ( json ) {
//Run function after table reloads
});
You can create a custom button in datatable. You can go to this documentation to know how it works. Now in the action you can call some function inside it when the user click it the button will call the function in javascript and do what you want inside it.
Here's example code.
$('#table_id').DataTable({
"serverSide": true,
"processing": true,
"ajax": function (data, callback, settings) {
$.ajax({
url: '/some url',
type: 'GET',
data: data,
success: function (data) {
console.log(data)
}
});
},
buttons: [
{ text: 'Add', name: 'btnAdd', action: function ( e, dt, node, config ) {
$.fn.addfunction();
}},
{ extend: 'selected', text: 'Edit', name: 'btnEdit', action: function ( e, dt, node, config ) {
$.fn.editfunction();
}},
{ extend: 'selected', text: 'Delete', name: 'btnDelete', action: function ( e, dt, node, config ) {
$.fn.deletefunction();
}},
],
"columns": [{
"title": "edit",
"data": null,
"className": "center",
"defaultContent": ' Edit / Delete '
}, {
"title": "name",
"data": "name"
}, {
"title": "id",
"data": "id"
},
]
});
$.fn.addfunction = function(){
//Your code here
}
$.fn.editfunction = function(){
//Your code here
}
$.fn.deletefunction = function(){
//Your code here
}
I added the idea of this document from datatables that create custom button and create and call function in jquery
There's also other way by using and giving id for the button. here's the example:
$('#table_id').DataTable({
"serverSide": true,
"processing": true,
"ajax": function (data, callback, settings) {
$.ajax({
url: '/some url',
type: 'GET',
data: data,
success: function (data) {
console.log(data)
}
});
},
buttons: [
{ text: 'Add', name: 'btnAdd',
attr:{
id: 'btnAdd'
}},
{ extend: 'selected', text: 'Edit', name: 'btnEdit',
attr:{
id: 'btnEdit'
}},
{ extend: 'selected', text: 'Delete', name: 'btnDelete',
attr:{
id: 'btnDelete'
}},
],
"columns": [{
"title": "edit",
"data": null,
"className": "center",
"defaultContent": ' Edit / Delete '
}, {
"title": "name",
"data": "name"
}, {
"title": "id",
"data": "id"
},
]
});
$(document).on('click', '#btnAdd', function(e)
{
e.preventDefault();
e.stopPropagation();
//your code here
});
$(document).on('click', '#btnEdit', function(e)
{
e.preventDefault();
e.stopPropagation();
//your code here
});
$(document).on('click', '#btnDelete', function(e)
{
e.preventDefault();
e.stopPropagation();
//your code here
});
Sorry for many Edit Hope it helps!

Store selected rows id

I have a datatable loaded from a query from my database. (+/- 10000 records)
The idea is that the user should be able to select multiple records to be later processed
First i thought to add a column with checkbox for the selection then when user is done with all his selection the application keep track of all selected rows then progress to the next step with "Next Button" some where on the page, but after 12 hours of trying i couldn't do it.
Then i thought to make it simpler by adding a button in each row so that every time the user clicks on this button the application save the selected id in a session variable.
<div class="panel-body">
<table id="userTable" class="table display compact order-column">
<thead>
<tr>
<th>Select</th>
<th>Name</th>
<th>City</th>
<th>Phone</th>
<th>Zipcode</th>
</tr>
</thead>
</table>
#section Scripts {
#Scripts.Render("~/bundles/datatable")
<script type="text/javascript">
$(document).ready(function () {
var ids;
var mytable = $('#userTable').DataTable({
"sDom": 'ltipr',
"bServerSide": true,
"ajax": {
"beforeSend": AjaxBegin,
"type": "POST",
"url": '/LocationModifier/UserHistory',
"contentType": 'application/json; charset=utf-8',
'data': function (data) { return data = JSON.stringify(data); },
'complete': AjaxComplete
},
"bProcessing": false,
"orderMulti": false,
"scrollX": true,
"deferRender": true,
"searchDelay": 7000,
"fixedHeader": {
"header": true,
"footer": true
},
"columnDefs": [
{ "defaultContent": "-", "targets": "_all" },
{ "className": "text-center custom-middle-align", "targets": [0, 1, 2, 3, 4, ] },
],
"colReorder": true,
"lengthMenu": [[10, 25, 50, 100], [10, 25, 50, 100]],
"columns": [
{
"title": "Select",
"data": "ID",
"searchable": false,
"sortable": false,
"render": function (data, type, full, meta) {
return '<span class="glyphicon glyphicon-pencil btn-sm btn-info"></span>';
}
},
{ "data": "Name", "orderable": false },
{ "data": "City", "orderable": true },
{ "data": "Phone", "orderable": true },
{ "data": "Zipcode", "orderable": false },
],
"order": []
});
});
</script>
}
public ActionResult AddToCache(int id)
{
GetRecordAndAddeToCache(id);
// what should i return here, the page should not be refreshed????
}
There's no problem to implement your initial approach:
use some global set that will store selected row id's, like var rowsSelected = new Set();
add/delete id of the row being checked to that global variable upon clicking selection checkbox:
$('.markSelected').on('click', function () {
const selectedRowId = dataTable.row($(this).closest('tr')).data().id;
$(this).prop('checked') ? rowsSelected.add(selectedRow) : rowsSelected.delete(selectedRow);
});
upon table re-rendering append checkboxes to the first column and set those checked if rendered row id is present within rowsSelected:
render: function (data) {
return `<input type="checkbox" ${rowsSelected.has(data.id) ? 'checked' : ''}></input>`;
}
The complete demo, implementing that concept:
//table source
const srcData = [
{id: 1, item: 'apple', cat: 'fruit'},
{id: 2, item: 'pear', cat: 'fruit'},
{id: 3, item: 'carrot', cat: 'vegie'},
{id: 4, item: 'tomato', cat: 'vegie'},
{id: 5, item: 'cucumber', cat: 'vegie'}
];
//global variable that stores selected item id's
const selectedRows = new Set();
//datatables initialization
const dataTable = $('#mytable').DataTable({
dom: 't',
data: srcData,
columns: [
{data: null, render: function(data){
return `<input class="markSelected" type="checkbox" ${selectedRows.has(data.id) ? 'checked' : ''}></input>`;
}},
{data: 'item', title: 'item'},
{data: 'cat', title: 'cat'}
]
});
//selection checkboxes click handler
$('#mytable').click('.markSelected', function(){
const selectedRowId = dataTable.row($(event.target).closest('tr')).data().id;
$(event.target).prop('checked') ? selectedRows.add(selectedRowId) : selectedRows.delete(selectedRowId);
});
//proceed to the next step with selected row id's
$('#nextStep').on('click', function(){
console.log([...selectedRows]);
});
<!doctype html>
<html>
<head>
<script type="application/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="application/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
</head>
<body>
<table id="mytable"></table>
<button id="nextStep">Next Step</button>
</body>
</html>
You can use datatable's Row selection feature to achieve what you are trying to do.
$(document).ready(function() {
var table = $('#userTable').DataTable();
$('#userTable tbody').on( 'click', 'tr', function () {
$(this).toggleClass('selected');
} );
$('#submitButtonId').click( function () {
alert( table.rows('.selected').data().length +' row(s) selected' );
// You can use table.rows('.selected').data() to get all the selected Data
} );
} );
Reference

How to get particular column in responsive jquery datatable for small Screen

I have implemented responsive jquery datatable in one of my project.
At the end of each row there is edit/detail link.
If i click edit/detail link:
1)Large Screen - It picks the UseID(Which is first Column in a row), so that i can edit that User.
2)Small Screen - Because of responsiveness the row will splitted as show below. It doesnot pick that User ID.
Large Screen Edit/Detail is Last row
Large Screen after clicking Edit link
Small Screen See Edit/detail link which is splitted
I am not able to get the UserID alert when i click edit link whenever the screen is small.
My Code.
<table id="myExample" class="display responsive nowrap">
<thead>
<tr>
<th>User Name</th>
<th>First Name</th>
<th>LastName</th>
<th>Street</th>
<th>City</th>
<th>Zip</th>
<th>State</th>
<th>Email</th>
<th>Edit</th>
</tr>
</thead>
</table>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.dataTables.min.js"></script>
<script src="~/Scripts/dataTables.responsive.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var table = $('#myExample').DataTable({
"ajax": {
"url": "/Admin/LoadData",
"type": "GET",
"datatype": "json"
},
"columns": [
{ "data": "Usr_Nm", "autowidth": true },
{ "data": "FirstName", "autowidth": true },
{ "data": "LastName", "autowidth": true },
{ "data": "Street", "autowidth": true },
{ "data": "City", "autowidth": true },
{ "data": "Zip", "autowidth": true },
{ "data": "Sate", "autowidth": true },
{
data: null,
defaultContent: 'Edit/Detail',
orderable: false
}
]
});
$('#myExample').on('click', 'a.Edit', function (e) {
var UserId = $(this).closest('tr.').find('td').find('.sorting_1').text();
$.ajax({
url: '/Admin/UserEdit',
type: "GET",
data: { 'id': UserId },
dataType: "json",
success: function (response) {
// alert('1:');
// alert(response);
if (response.isRedirect) {
// alert('1');
window.location.href = response.redirectUrl;
//window.location.href = response.redirectUrl;
}
// }
},
error: function (response) {
alert("Some error");
}
});
});
})
</script>
To get UserID:
var UserId = $(this).closest('tr.').find('td').find('.sorting_1').text();
Inspect Element in Large Screen
Inspect Element in Small Screen:
You must go through the dataTables API in order to get data for columns not present in the DOM (removed due to responsiveness).
You can get the all values for a certain row by table.row(<tr-node>).data() :
$('#myExample').on('click', 'a.Edit', function (e) {
var data = table.row($(this).closest('tr')).data()
//if it is "User Name" / first column you are after
var userId = data[0]
...
})

How to use datatables in ajax

I want to try pagination using datatables.net via ajax.
I have 2 input fields which sends start date and end date and following is the table structure
<table class="table table-hover" id="example">
<thead>
<tr>
<th>Loan ID</th>
<th>Date</th>
<th>Loan Amount</th>
<th>Loan Type</th>
</tr>
</thead>
<tbody id="amount"></tbody></table>
when the button is clicked,I am calling this function
$('#recv').click(function(){
var fromDate=$('#from').val();
var toDate=$('#to').val();
var test=$.ajax({
type: "GET",
url: "/project/getDetails",
data:{"fromDate":fromDate,"toDate":toDate},
dataType:"json",async:false
}).responseText;
var result = eval('('+test+')');
$('#example').dataTable( {
"bServerSide": true,
"sAjaxSource": result,
"bProcessing": true,
"aoColumns": [
{ "sName": "Loan_ID",
"bSearchable": false,
"bSortable": false
},
{ "sName": "Date" },
{ "sName": "Loan_Amount" },
{ "sName": "Loan_Type" }
]
} );
When Ever I click on the button then I get error in alert box saying datatables warning id=example ajax error
Can anybody please tell me how to solve?
Let datatables take care of the ajax call:
var oTable = $('#example').dataTable( {
"bServerSide": true,
"iDeferLoading": 1,
"sAjaxSource": "/project/getDetails",
"fnServerParams": function (aoData) {
aoData.push({ "name": "fromDate", "value": $('#from').val() });
aoData.push({ "name": "toDate", "value": $('#to').val() });
},
"bProcessing": true,
"aoColumns": [
{ "sName": "Loan_ID",
"bSearchable": false,
"bSortable": false
},
{ "sName": "Date" },
{ "sName": "Loan_Amount" },
{ "sName": "Loan_Type" }
]
} );
$('#recv').click(function(){
oTable.fnDraw();
});
Points to note:
fnServerParams this passes your start & end date to the
getDetails function
iDeferLoading - prevent table population on page load
fnDraw() populates the datatable from your click event

JS dataTable plugin: handling json format other than standard datatable format

I am new to Datatables and trying to figure out this problem.
I have a server which oupts json in certain format(see below).I cant change that on server side.
**Note: I am using link http://www.json-generator.com/j/cftupHnpbC?indent=4 to emulate my server response just for checking.
I have 2 problems
Since My json response doesn't have aaData: thing required by dataTable, I cant seem to initiliaze it.
Even if I add aaData: by hand to json just for checking, dataTable cant count total records.How I can set that manually ?Since I cant change output from server.
JSBIN LINK:
http://live.datatables.net/dasuyaf/1/edit
HTML:
<table id="example" class="display" width="100%">
<thead>
<tr>
<th> </th>
<th>ID</th>
<th>Name</th>
<th>Text</th>
</tr>
</thead>
<tbody></tbody>
</table>
JS:
$(document).ready( function () {
var table = $('#example').dataTable({
"sAjaxSource": "http://www.json-generator.com/j/cftupHnpbC?indent=4",
"aoColumns": [{
"mData": "id",
"mRender": function (data, type, full) {
return '<input type="checkbox" name="chkids[]" value="' + data + '">';
}
}, {
"mData": "id"
}, {
"mData": "name"
}, {
"mData": "text"
}],
"bProcessing": true,
"bServerSide": true,
"sServerMethod": "GET",
"aoColumnDefs": [{
'bSortable': false,
'aTargets': [0]
}],
"fnDrawCallback": function (oSettings) {
console.log(this.fnSettings().fnRecordsTotal());
}
});
});
My Server Output: (cant change this)
[
{
"text": "Some text",
"name": "somedata",
"id": "89"
},
{
"text": "Some text",
"name": "somedata",
"id": "2"
},
{
"text": "Some text",
"name": "somedata",
"id": "12"
}
]
I suppose you could just request that JSON yourself, make an object out of it and pass it to your dataTable.
var aaData;
var table;
$(document).ready( function () {
$.ajax({
url: 'http://www.json-generator.com/j/cftupHnpbC?indent=4'
}).done(function(data){
aaData = data;
table = $('#example').dataTable({
"aaData": aaData,
"aoColumns": [{
"mData": "id",
"mRender": function (data, type, full) {
return '<input type="checkbox" name="chkids[]" value="' + data + '">';
}
}, {
"mData": "id"
}, {
"mData": "name"
}, {
"mData": "text"
}],
"bProcessing": true,
"aoColumnDefs": [{
'bSortable': false,
'aTargets': [0]
}],
"fnDrawCallback": function (oSettings) {
console.log(this.fnSettings().fnRecordsTotal());
}
});
});
} );
I removed bServerSide - I don't think there's any way you can make use of it if you can't change your server response. Also removed sServerMethod.

Categories