Change only selected row/cell in DataTable - javascript

I have this piece of code where table cell is edited and updated.
$.ajax({
url: url_base + 'update',
type: "POST",
data: params,
dataType: 'json', // data type
contentType: "application/json; charset=utf-8",
success: function(res) {
/*var params = {};
callFunction("getWords", params,
function(bSuccess, res) {
$('#example').dataTable().fnDestroy();
var table = $('#example').DataTable({
data: res,
"columns": [
{ "bSortable": false, "targets": 0, "data": 'UserWord' },
{ "bSortable": false, "targets": 1, "data": 'UserWordAlt1' },
{
"targets": 2,
"data": 'UserWord',
"render": function(data) {
return '<button alt="Edit" class="btn btn-primary" value="' + data + '" onclick="edit(this)"><i class="far fa-edit"></i></button> ' + '<button class="btn btn-danger" id=' + data + ' onclick="del(this)"><i class="fas fa-trash-alt"></i></button>'
}
}
],
"order": [
[1, 'asc']
]
});
}
);*/
$('#updateAnliegenModal').modal('hide');
alertify.success('New word updated successfully');
},
error: function(xhr, resp, text) {
console.log(xhr)
}
})
});
The thing is, when I update row I want to affect changes only for that row. Not to refresh the dataTable. In my current case I lost focus from that row which I am updating because table is reloaded again and rows are sorted by new data. Another problem is when I search for a specific word using the search feature of DataTable. If I want to update that found word I want to display only that searched word, not to reload the whole table.
I commented that part where new table is reloading... Actually I am calling again the same getWords function which on success destroys the current datatable and reloads the new one.

Related

how to save table state even after changing table pages

I have a dataTable that displays data from a database. I'ts displayed in a bootstrap modal and there is an option in each row to delete the row.
Here's the jquery that gets the data from the database:
function cart_contents() {
$.ajax({
url: "cartContents.php",
type: "POST",
dataType: "JSON",
success: function(data){
var table = $('#cart-content').dataTable();
table.fnDestroy();
table.dataTable({
"aaData": data,
"scrollX": false,
"lengthChange": false,
"ordering": false,
"pageLength": 6,
"language": {
"info": "Number of items: _TOTAL_"
},
"searching": false,
"aoColumns": [
{"sTitle": "Product", "mData": "product"},
{"sTitle": "Price", "mData": "price"},
{"sTitle": "Qty.", "mData": "quantity"},
{
"sTitle": "Edit", "mData": "id", "render": function (mData, type, row, meta) {
return '<button class="btn btn-xs btn-success" onclick="sample(' + mData + ')">Edit</button>';
}
},
{
"mData": "id", "render": function (mData, type, row, meta){
return "<span style='cursor: pointer' class='close' onclick='remove_product(this," + mData + ")'>x</span>";
}
}
]
})
}
}
Here's the remove_product:
function remove_product(these, id){
var i = these.parentNode.parentNode.rowIndex;
document.getElementById("cart-content").deleteRow(i);
$.ajax({
type: "POST",
url: "remove_product.php",
data: {product_id: id},
success: function(data){
alert(data);
}
})
}
Now, the data may or may not exceed a single page on the table since it is set to display 6 rows. Therefore, there is a chance that there may be pagination. Whenever the 'x' is clicked to remove the row, it removes it on the page, and successfully deletes it in the database.
However, when I scroll to the next page of the table and go back previously, the row that was deleted comes back. How would I go about deleting it permanently, since it no longer exists in the database? I need to do this without reloading the modal.

Datatables: dynamic page load in modal, based on row values

I am trying something really complex here, and I have not worked out a way to implement a solution yet. The part I work on looks like this:
1. simple page A that dynamically loads datatable from db.Last col is a button.
2. an html page B that loads different things according to 2 values stored at at local storage. these are available in the aforementioned table.
Now the part I cannot figure out:
3. Into the simple page A, there is a modal div. I want to load the B page into this modal on button click, and load different data, according to the values stored at local storage.
Here is my code so far:
function getadminprojects(){ //function that dynamically loads datatable
$.ajax({
url: "http://....../CustomServices/DBDistApps",
type: "GET",
dataType: 'json',
async: false,
success: function(data) {
$('#projectsdt').show();
projectsTable = $('#projectsdt').DataTable({
"pageLength": 10,
"data": data,
"scrollX": true,
"order": [[ 4, "desc" ]],
//"aaSorting": [],
"columns": [
{ "data": "code" },
{ "data": "descr" },
{ "data": "manager" },
{ "data": "customer" },
{ "data": "link_date" },
{ "data": "delink_date"},
{ "data": "type"},
{
"data": null,
"defaultContent": "<button class='btn btn-warning' onclick='openmodal2();'>button1</button>"
},
{
"data": null,
"defaultContent": "<button class='btn btn-success' onclick='localStorage.setItem('username',"+row.customer+");localStorage.setItem('projectid',"+row.code+"); projectpopmodal(); '>button2</button>"
},
] ,
});
$('#projectsdt thead').on('click', 'tr', function () {
var data2 = table.row( this ).data();
alert( 'You clicked on '+data2[0]+'\'s row' );
} );
$('#projectsdt').show();
$('#projectsdt').draw();
}
});
}
function projectpopmodal(){
$('#showfreakinmap').load('newprojects.html');
$('#fsModal').modal('show');
}//function to load page B into modal of page A
Thank you in advance!

Jquery Datatables get row data as string or object on button click

I'm attempting to get a row of data based on button click event. I can manage to find the row and read the results as text, but I want the data cast as a string or an object. Below is my current code:
$.ajax({
url: "SympsService.asmx/GetSymptoms",
method: "post",
dataType: "json",
data: JSON.stringify({
organ_name: "toes"
}),
contentType: "application/json",
success: function(data) {
var sympList = 'GetSymptoms' ? JSON.parse(data.d) : data.d;
createDataTable('#symptomsTable', sympList);
function createDataTable(target, data) {
$(target).DataTable({
destroy: true,
paging: false,
searching: false,
info: false,
data: data,
columnDefs: [{
targets: [-1],
render: function() {
return "<button type='button'>" + ('Choose') + "</button>"
}
}],
columns: [{
'data': 'Sympt',
'title': 'toes Symptoms'
}, {
'data': null,
'title': 'Action'
}]
});
}
$('#symptomsTable').on("click", "tbody button", function() {
var id = $(this).closest("tr").find("td:nth-child(1)").text(); //this show perfectly
var id = $(this).closest("tr").find("td:nth-child(1)").data(); //this show undefined
var id = $(this).closest("tr").find("td:nth-child(1)").toString(); //this show {object Object}
console.log(id);
})
},
});
Any kind of help is appreciated.
To find the data object for the whole row:
$("#symptomsTable').DataTable().rows($(this).closest("tr")).data()
to find it for the particular cell:
$("#symptomsTable").DataTable().cells($(this).closest("td").siblings().eq(0)).data()

DataTables not initialising twice on the same page?

I am trying to use DataTables twice on two different modals, the problem I'm having is the second modal that opens the DataTable isn't being initialised?
CodePen of the process -
http://codepen.io/kieronapple/pen/WwzrgP
How it should work -
First modal opens first DataTables initialises
Press manage on the first modal, second modal opens. But DataTables doesn't initialise?
Function to initialise both tables
function getValidTags(type){
var ruleID = $('.ruleID').val();
switch(type){
case "validTags":
var table = $('.valid-tags').DataTable({
"ajax": {
"url": "/ajax/getValidTags.php",
"type": "POST",
"data": {
ruleID: ruleID,
type: type
},
},
"columnDefs": [{
"targets": 2,
"render": function(data, type, full, meta){
return '<button class="btn btn-default btn-sm manageAutofixes" type="button">Manage</button> <button class="btn btn-danger btn-sm deleteValid">Delete</button>';
}
}],
destroy: true
});
break;
case "autofixes":
alert('hi');
var table2 = $('.autofixes-table').DataTable({
"ajax": {
"url": "/ajax/getValidTags.php",
"type": "POST",
"data": {
ruleID: ruleID,
type: type
},
},
"columnDefs": [{
"targets": 2,
"render": function(data, type, full, meta){
return '<button class="btn btn-default btn-sm manageAutofixes" type="button">Manage</button>';
}
}],
destroy: true
});
break;
}
}
Function to action first DataTable
$('input[class="val_list"]').click(function() {
$('.ruleID').val($('#mongoid').val());
$('.validation-list-modal').modal('show');
$('.validTagsTable').empty();
if ($('.val_list').is(':checked')) {
$(".tags, .tm-input, .new-tag, .allow_null_div, #null-label, .auto-fix").show();
}
getValidTags('validTags');
});
Function to action second DataTable
$('.valid-tags').on('click', '.manageAutofixes', function(){
$('.autofixes-modal').modal('show');
getValidTags('autofixes');
})

How to delete a row without Ajax request

Using jQuery DataTables 1.9.4, I simply post row ID to server and when it's deleted from the database and comes back to ajax success() function I use fnDeleteRow() row function to delete this row from the table.
But this triggers fnDraw() function init and makes an Ajax request to the server that is unnecessary.
How can I simply delete this row and arrange table on client side ?
confirmDelete = function()
{
var data = {
"rowid_":rowid
};
$.ajax({
url:"../../Controller/ObjectController.php5",
type:"POST",
dataType: "json",
data: data,
success: function(data) {
debugger
if(data.Success)
{
tableObjects.fnDeleteRow($("#tr_"+rowid),function(){
event.theme ='lime';
event.heading ='<i class=\'fa fa-check\'></i> Process Completed';
event.message ='Row deleted successfully.';
ntf(event);
});
}
here is my taable definition:
var tableObjects = $("#objectTable").DataTable({
"bProcessing": false,
"bServerSide": true,
"sAjaxSource": "../../Controller/ObjectController.php5",
"aoColumns": [
{ "mDataProp": "NAME"},
{ "mDataProp": "TYPE"},
{ "mDataProp": "IP"},
{ "mDataProp": "REMARK"},
{"mDataProp": "btnEdit"},
{"mDataProp": "btnDelete"}
],
"fnServerData": function (sSource, aoData, fnCallback){
aoData.push({"name":"tablename","value":"objects"})
debugger
$.ajax({
"dataType": "json",
"contentType": "application/json; charset=utf-8",
"type": "GET",
"url": sSource,
"data": aoData,
"success": function(result){
policyCount = result["iTotalRecords"];
$.each(result.aaData, function(index,value){
result.aaData[index]["btnEdit"] ="<a id=\"btnEdit\" class=\"btn btn-sm btn-success\" style=\"border-radius:4px\" onclick=\"fillFormwithDatasforEdit('"+value.NAME+"','"+value.REMARK+"','"+value.TYPE+"','"+value.IP+"')\" href=\"#mdlObjects\" data-toggle=\"modal\"><i class=\"fa fa-edit\"></i> Edit </a>";
result.aaData[index]["btnDelete"] ="<a class=\"btn btn-sm btn-danger\" href=\"#basic\" style=\"border-radius:4px\" onclick=\"setModalTitle('"+value.NAME+"','DeleteObject')\" data-toggle=\"modal\"><i class=\"fa fa-trash-o\"></i> Delete </a>";
result.aaData[index]["REMARK"] ="<a class=\"btn btn-sm btn-info\" style=\"border-radius:4px\" onclick=\"setremark('"+value.NAME+"','"+ value.REMARK +"')\" data-toggle=\"modal\" href=\"#full\"><i class=\"fa fa-comment\"></i> Remark</a>";
});
fnCallback(result);
},
error: function (xhr, textStatus, error){
if (typeof console == "object") {
console.log(xhr.status + "," + xhr.responseText + "," + textStatus + "," + error);
}
}});
},
"oLanguage": {
"sLengthMenu": '<select>' +
'<option value="5">5</option>' +
'<option value="10">10</option>' +
'<option value="20">20</option>' +
'<option value="30">30</option>' +
'<option value="40">40</option>' +
'<option value="50">50</option>' +
'</select> Show'
},
"fnCreatedRow": function( nRow, aData, iDataIndex ) {
objectname = aData["NAME"];
newRowID = "tr_" +objectname;
$(nRow).attr('id', newRowID);
$(nRow).find('td').each (function(index) {
newRowID = index==0?objectname+"_objectname":index==1?objectname+ "_type"
:index==2?objectname+"_ipaddress":index==3?objectname+"_btnremark"
:index==4?objectname+ "_btnedit":index==5?objectname+"_btndelete":"";
$(this).attr('id', newRowID);
});
},
"fnDrawCallback": function(){
},
"aaSorting": [
[2, 'asc']
],
"aLengthMenu": [
[5, 15, 20, -1],
[5, 15, 20, "All"] // change per page values here
],
"iDisplayLength": 5
});
Client-side processing mode
In client-side processing mode ("bServerSide": false), fnRowDelete() doesn't trigger Ajax request.
See this JSFiddle for demonstration. Look for Request in the console when the request is made.
Server-side processing mode
However, in server-side processing mode ("bServerSide": true), fnRowDelete() will trigger Ajax request.
Notes
API method fnRowDelete() has a third optional boolean argument that determines whether table should do a redraw. For example:
oTable.fnRowDelete(0, function(){ console.log('Deleted'); }, false);
If re-draw is not request, you would be responsible to re-draw the table yourself later with fnDraw() which also accepts optional boolean argument that determines whether to re-filter and resort the table before the draw. For example:
oTable.fnDraw(false);

Categories

Resources