How to delete a row without Ajax request - javascript

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

Related

Pagination in Jquery Datatable in asp.net webforms

I have an API, which accepts page number and page size as a parameter to return user details.
Loading data to the jquery data table. Needs to pass page number and size to API for fetch the data each time. How can I get and pass the page number to webmethod and enable next button all time. Because when i loaded first time data it only shows page number as 1 and Next button is disabled.
var tableUserDetails = $("#grdUser").DataTable({
processing: true,
filter: true,
orderMulti: false,
paging: true,
searching: true,
bFilter: true,
bsort: true,
bInfo: true,
pagingType: "simple",
columns: [{ "data": "Id" },
{ "data": "Name" },
{ "data": "userName" },
{ "data": "email" },
{ "data": "role" }
]
});
function getUsers() {
var info =tableUserDetails.page.info();
$.ajax({
data: '{pageNumber:' + info.page+1 + ', pageSize:' + 10 + '}',
type: "POST",
url: "MyPage.aspx/GetUsers",
contentType: Constants.ContentType,
error: function (XMLHttpRequest, textStatus, errorThrown) {
debugger;
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
},
});
}
I think that you are looking for this: DataTables server side processing. The configuration you have is not loading partially the data. It assumes you have all the rows when you set the dataset.
$(document).ready(function() {
$('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": "../server_side/scripts/server_processing.php"
} );
} );
And the format of the returned data should be like this:
{
"draw": 3,
"recordsTotal": 57,
"recordsFiltered": 57,
"data": [
[
"Airi",
"Satou",
"Accountant",
"Tokyo",
"28th Nov 08",
"$162,700"
],
/* etc */
An example of C# like response:
/// <summary>
/// Resultset to be JSON stringified and set back to client.
/// </summary>
[Serializable]
[SuppressMessage("ReSharper", "InconsistentNaming")]
public class DataTableResultSet
{
/// <summary>Array of records. Each element of the array is itself an array of columns</summary>
public List<List<string>> data = new List<List<string>>();
/// <summary>value of draw parameter sent by client</summary>
public int draw;
/// <summary>filtered record count</summary>
public int recordsFiltered;
/// <summary>total record count in resultset</summary>
public int recordsTotal;
public string ToJSON()
{
return JsonConvert.SerializeObject(this);
}
}
Edit - How to post with ajax
$(document).ready(function () {
$('#mytable').DataTable({
processing: true,
serverSide: true,
ajax: {
data: '{pageNumber:' + info.page+1 + ', pageSize:' + 10 + '}',
type: "POST",
url: "MyPage.aspx/GetUsers",
contentType: Constants.ContentType,
error: function (XMLHttpRequest, textStatus, errorThrown) {
debugger;
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
}
});
});

jqGrid filterToolbar only works with some columns

When I try searching for the string Test in the column "Erstellt Von", I get no results. There's no error in the console either.
This is the codepart I used:
var colUserTemplate = {
width: 160, align: 'left',
formatter: function (cellvalue, options, rowObject) {
return "Test";
}
}
In another column, the filtering works perfectly fine:
Here's how grids are loaded and the filterToolbar:
function loadGrid(listname, query, divname, colnames, colmdodel, showFilter, showExcelExport) {
$("#" + divname).jqGrid({
datatype: function () { loadGridData(listname, query, divname); },
colNames: colnames,
colModel: colmdodel,
height: "100%",
loadonce: true,
rowNum: 9999,
gridComplete: function () {
$("#" + divname + "no").html(" [" + $("#" + divname).jqGrid('getGridParam', 'records') + "]");
$("#" + divname).jqGrid('setGridParam', { datatype: 'local' });
},
ondblClickRow: function (rowid, iRow, iCol, e) {
onDoubleClickGrid(rowid, iRow, iCol, e, divname, listname);
}
});
if (showFilter) {
$("#" + divname).jqGrid('filterToolbar', {
autosearch: true,
stringResult: false,
searchOnEnter: true,
defaultSearch: "cn",
});
}
}
I tried using
if (showFilter) {
$("#" + divname).jqGrid('filterToolbar', {
autosearch: true,
stringResult: true,
searchOnEnter: true,
defaultSearch: "cn", ignoreCase: true
});
}
but it didn't change anything.
If you want to have a look, here's the full code.
Been trying to fix this issue for hours, so any help is appreciated!
EDIT:
When writing this:
var thegrid = $("#" + divname)[0];
console.log("data.d.results: " + data.d.results);
thegrid.addJSONData(data.d.results); //Binding data to the grid
console.log("thegrid:" + thegrid.innerHTML);
I get the following result:
Here's the expanded object:
You use a function to load the data:
function loadGridData(listname, query, divname) {
$.ajax({
url: "/tools/AKG/_api/web/lists/getbytitle('" + listname + "')/Items?" + query,
type: "GET",
headers: { "Accept": "application/json;odata=verbose" },
success: function (data, textStatus, xhr) {
var thegrid = $("#" + divname)[0];
thegrid.addJSONData(data.d.results); //Binding data to the grid
},
error: function (xhr, textStatus, errorThrown) {
alert("error:" + JSON.stringify(xhr));
$('#' + divname + 'records').html(" [0]");
}
});
}
In the success function data.d.results contain your grid data. Before to put this data in addJSONData loop over that column and change its value or better do it at server if possible

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.

Load row information from DataTable created with AJAX

I have the next form.
This table is created with an AJAX call, here is the code:
$.ajax({
type: 'POST',
url: urlServer + "../webserviceURL", //URL del Web Service
data: '{"us":"' + sessionStorage.Usuario + '"}',
dataType: 'json',
contentType: 'application/json',
timeout: 600000,
error: function (xhr) {
lineas += '<tr><th colspan="8" class="text-center">No se encontraron registros de los cursos.</th></tr>';
$('#Tabla6').html(lineas);
bootbox.alert("No se pudo cargar los cursos.");
},
success: function (data) {
$('#Tabla6').dataTable({
"aaData": JSON.parse(data.d),
"aoColumns": [{
"mDataProp": "Id"
}, {
"mDataProp": "Nombre"
}, {
"mDataProp": "ContraseƱa"
}, {
"mDataProp": "Tipo"
}, {
"mDataProp": "Correo"
}, {
"mData": "",
"bSortable": false,
"mRender": function (oObj) {
return '<span class="btn btn-success fa fa-edit"></span>';
}
}]
});
}
});
Works fine but I want to load the row information when user click the "pencil button" and I dont know exactly how to do this. The only thing I need is load the row information to this method:
$('#Tabla6').on('click', '.glyphicon-edit', function () {
var id = $(this).attr('data-id');
editarDatosUsu(id);
});
editarDatosUsu Method:
function editarDatosUsu(id) {
if ($('#U' + id).length) {
var id = $('#U' + id).attr('data-id');
$('#IdUs').val(id);
var rev = $('#U' + id + '-1').html();
var pass = $('#U' + id + '-2').html();
var tipo = $('#U' + id + '-3').html();
var mail = $('#U' + id + '-4').html();
$('#user').val(rev);
$('#pass').val(pass);
$('#tipo').val(tipo);
$('#mail').val(mail);
}
Here's what I do:
$("#dashboardTable").on( 'click', '.approveLink', function () {
var tableRow = table.row( $(this).parents('tr') );
var row = $(this).parents('tr');
approveDashboard(tableRow.data().id, row);
} );
(where table is the datatable)

Uncaught TypeError: Cannot read property 'AutoFill' of undefined

I am using jquery datatables 1.10 with ASP.NET 4.5. The code works with no issues when debugging. When I run it, it doesn't fill the data in table and leaves as empty data set. This error showed up in FireBug.
Code:
$('#dtGroups').dataTable({
"oLanguage": {
"sZeroRecords": "No records to display",
"sSearch": "Search "
},
"aLengthMenu": [[25, 50, 100, 150, 250, 500, -1], [25, 50, 100, 150, 250, 500, "All"]],
"iDisplayLength": 25,
"bSortClasses": false,
"bStateSave": false,
"bPaginate": true,
"bAutoWidth": false,
"bProcessing": true,
"bServerSide": true,
"bDestroy": true,
"bJQueryUI": false,
"sAjaxSource": "<%= ResolveUrl("~/Handler/GetData") %>",
"sPaginationType": "full_numbers",
"bDeferRender": true,
"fnServerParams": function (aoData) {
},
"aoColumnDefs": [
{
"bVisible": false,
"aTargets": [0]
},
{
"aTargets": [1],
"mData": null,
"mRender": function (data, type, row) {
var enc = encodeURI(row[1]);
return "<a href='SomePage.aspx?qs="+enc+"'>" + row[1] + "</a>";
}
}
],
"fnServerData": function (sSource, aoData, fnCallback) {
var jsonAOData = JSON.stringify(aoData);
$.ajax({
"dataType": 'json',
"contentType": "application/json; charset=utf-8",
"type": "POST",
"url": sSource,
"data": "{ jsonAOData : '" + jsonAOData + "' }",
"success":
function (result) {
var json = jQuery.parseJSON(result.d);
console.log(json);
fnCallback(JSON.parse(result.d))
},
"error":
function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest + ": Error: " + XMLHttpRequest.responseText + ", " + textStatus + ": " + errorThrown);
}
});
}
});
Any help would be appreciated.
Please read the documentation for options http://datatables.net/reference/option/
Also read how to convert your options to datatables 1.10. https://datatables.net/upgrade/1.10-convert
fnServerData is not an option datatables accepts.

Categories

Resources