how to save table state even after changing table pages - javascript

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.

Related

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!

Change only selected row/cell in DataTable

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.

Is it possible to use Ajax success result to populate jQuery DataTable

I would like to declare my jQuery datatable without initially populating it and later when calling Ajax functions, I would like to take the results and use that as the data source for my data table, right now I am making multiple Ajax calls for the same purpose and I would like to eliminate this if possible.
$.ajax({
type: "GET",
url: "/Receiving/GetUnorderedParts",
datatype: "html",
data: { "id": button.attr("data-ponumber") },
success: function(data) {
var orderButton = $(".js-Order");
orderButton.removeClass("invisible");
tbl = $("#UnorderedDetail")
.DataTable({
"destroy": true,
"searching": false,
"ordering": false,
"lengthChange": false,
"pagingType": "full_numbers",
"paging": true,
"lengthMenu": [10, 25, 50, 75, 100],
ajax: {
url: "/Receiving/GetUnorderedParts",
data: { "id": button.attr("data-ponumber") },
datasrc: ""
},
"columnDefs": [
{
targets: -1,
className: 'dt-body-center'
}
],
columns: [
{
data: "Description"
},
{
data: "VendorPartNumber"
},
{
data: "Quantity"
},
{
data: "CartID",
render: function(data) {
return "<button class='btn btn-danger js-delete' data-cart-id=" +
data +
">Delete</button>";
}
}
] //EOColumns
}); //EODataTable
} //EOSuccess
}); //EOInnerAjax
You can call a function to build the data table on success something like:
$.ajax({
type: "GET",
url: "/Receiving/GetUnorderedParts",
datatype: "html",
data: { "id": button.attr("data-ponumber") },
success: function(data) {
var orderButton = $(".js-Order");
orderButton.removeClass("invisible");
createTable(data);
}
});
and the function can take in the array of objects and create a data table:
function createTable(dataSet)
{
$('#example').DataTable({
data: dataSet,
"aoColumns": [{
"sTitle": "Description",
"mData": "Description"
}, {
"sTitle": "VendorPartNumber",
"mData": "VendorPartNumber"
}, {
"sTitle": "Quantity",
"mData": "Quantity"
}, {
"sTitle": "CartID",
"mData": "CartID",
"mRender": function(data) {
return "<button class='btn btn-danger js-delete' data-cart- id=" + data + ">Delete</button>";
}}]
});
}
Check out a working example . It takes in an array of objects and create a datatable.

JQuery Data table - Get a value of a different column from another column

How do I get the value of checklistclient_id column and insert into the onchange event at the last column?
When the change of checkbox value occurs, it brings the checklistclient_id to the togglecheck function.
function loadClientChecklist(url){
var rt_hash = decodeUrl(url);
var id = rt_hash[0].replace("id=", "");
$.ajax({
type: 'POST',
url: '../model/get_set_ajax2.php?req=21',
data: 'cid=' + id,
success: function (results) {
console.log(results);
$('#clchecklist_tab').DataTable({
"paging": false,
"searching": true,
"info": false,
"ordering": false,
"aaData": $.parseJSON(results),
"aoColumns": [
{"mData": "checklistclient_id", "visible": false},
{"mData": "description"},
{"mData": "is_checked", "mRender": function (data) {
return '<input type="checkbox" onchange="togglecheck('+ checklistclient_id +')" value='+data+'/>';
}
}
]
});
}
});
You should use row created callback Then you can set id to trs.
"createdRow": function ( row, data, index ) {
$(row).data("checklistclient_id", checklistclient_id );
}
Now, you know all id of tr. Lets say that your check box has class called cb
$("#clchecklist_tab" ).delegate( ".cb", "change", function() {
togglecheck($(this).closest("tr").data(checklistclient_id))
})"

Add Links to data rows result on Datatables using ASP VB.Net

I am using DataTables for my ASP project, I would like to have the first column to contain links.
Here's my code:
$.ajax({
data: JSON.stringify(CardCode),
dataType: "json",
url: "/WebServices/Invoice/BusinessPartner.asmx/GetJsonPrevTrans",
type: "POST",
contentType: "application/json; charset=utf-8",
success:
function (ef1) {
console.log(CardCode);
console.log(JSON.parse(ef1.d))
console.log(ef1)
$("#bpPrevJSONTrans").val(ef1.d).trigger('change');
var parsed = JSON.parse(ef1.d);
var bpPrevDt = $('#bpPrevTransData').DataTable({
retrieve: true,
responsive: true,
"bJQueryUI": true,
"bProcessing" : true,
"aaData": parsed,
"aoColumns": [
{ "sTitle": "Test", "mData": "test" },
{ "sTitle" : "Document Number","mData": "DocNum" },
{ "sTitle" : "Description", "mData": "Dscription" },
{ "sTitle": "Amount", "mData": "DocTotal", "sType": "numeric" }
]
});
}
});
Thank you!
If you need the Test one to contain a link then change the aoColumns arrays 1st element to below line,
{ "sTitle": "Test",
"mData": "test",
"fnRender":function(obj, type){
return "<a href='Your link goes here' >Click here</a>";
}
}
Instead of putting a link button in row details for me to do my function such as editing, I just used the fnRowCallBack function of the datatable. See code below:
"fnRowCallback": function (nRow, aData, iDisplayIndex) {
// Bind click event
$(nRow).click(function () {
$('#viewInvoiceEntry').modal('show');
//Append Information on Modal:
$('#viewInvRefNum').val(aData.DocNum).attr("readonly", "readonly");
$('#viewInvDesc').val(aData.Dscription).attr("readonly", "readonly");
$('#viewInvAmnt').val(aData.DocTotal).attr("readonly", "readonly");
$('#viewInvDocDate').val(aData.DocDate).attr("readonly", "readonly");
$('#viewInvSrvc').val(aData.ItemName).attr("readonly", "readonly");
$('#viewInvCompGrp').val(aData.GroupName).attr("readonly", "readonly");
$('#viewInvCompName').val(aData.CompName).attr("readonly", "readonly");
$('#viewInvRemarks').val(aData.Comments).attr("readonly", "readonly");
//alert('You clicked on ' + aData.DocNum + '\'s row');
});
return nRow;
}

Categories

Resources