How to re-oder serial numbers after remove deleted row from datatable - javascript

After i deleted row the serial number column number are not re-ordered
I have Delete button in each row on click calling Ajax to delete record from data. It's deleting record from data base, after deleted recording I want to display remain data and remove particular row in table but it's changing pagination and refreshing the whole table.
var owner_table = null;
$(document).ready(function () {
owner_table = $('#owners_table').DataTable();
});
function deletehouseowner(oid, rid) {
$.ajax({
dataType: "HTML",
type: "POST",
data: {
"oid": oid
},
url: "houseowner_delete.php",
success: function (msg) {
if (msg === "failure") {
} else {
event.preventDefault();
var table = 'owners_table';
var row = $(this).closest('tr');
var id = row.attr("id");
setTimeout(function () {
var siblings = row.siblings();
owner_table.row($('#row_' + rid)).remove().draw();
siblings.each(function (index) {
$(this).children().first().text(index + 1);
});
}, 100);
}
}
});
}
Screenshot:

SOLUTION
API method draw() accepts optional parameter that controls how the table should be updated.
Pass false to draw() function to preserve current page, see the code below:
owner_table.row($('#row_'+rid)).remove().draw(false);
DEMO
See this jsFiddle for code and demonstration.

Related

Slickgrid changes the ID from my data and dont clean up the empty row

Im trying to update my grid without the need for refreshing! Right now, it updates only the grid, but dont know why, it changes the id to the last one inserted and dont "clean up" the empty row! When I try to insert data, it clears it .
Im kinda new with ajax and slickgrid! I've tried to see the ajax example from slickgrid, but I got some errors!
Do I need to re-upload the onCellChange and so on ? I just wanted to update th grid with the new data.
Any help?
Thanks in advance
So, I've tried re-draw the table re-using my actual drawning code, but im failling to re-draw with correct data.
Function to re-draw grid
function desenhaGrid() {
$("#myGrid").ready(function () {
$(function () {
$.ajax({
type: "GET",
url: '/SlickGrid/GetData',
dataType: 'json',
success: function (jsonResult) {
for (var key in jsonResult) {
if (jsonResult.hasOwnProperty(key)) {
//print table
var d = (data[key] = {});
for (var i = 0; i < data.length; i++) {
d["#"] = i + 1;
}
d["id"] = jsonResult[key].id;
d["t_nome"] = jsonResult[key].t_nome;
d["t_prof"] = jsonResult[key].t_prof;
d["t_data"] = jsonResult[key].t_data;
d["t_morada"] = jsonResult[key].t_morada;
d["t_percCompleto"] = jsonResult[key].t_percCompleto;
}
}
grid = new Slick.Grid("#myGrid", dataView, columns, options);
dataView.beginUpdate();
grid.invalidateAllRows();
dataView.setItems(data);
grid.render();
dataView.endUpdate();
}
});
});
});
}
and this is my onAddNewRow
grid.onAddNewRow.subscribe(function (e, args) {
var idData = jsonResult[key].id + 1;
var item = { "id": idData, "t_nome": '', "t_prof": '', "t_data": '', "t_morada": '', "t_percCompleto": '' };
$.extend(item, args.item);
dataView.addItem(item);
//if user press enter
grid.onKeyDown.subscribe(function (e) {
var keyPressed = event.keyCode || event.which;
if (keyPressed == 13) {
alert("add");
var myJSON = JSON.stringify(item);
$.post("/SlickGrid/addGridEnter", $("input[name=mydata]").val(myJSON));
console.log(myJSON);
desenhaGrid();
}
});
});
I expected it to re-draw my grid with all the data. Instead, its changing all the id's to the last one inserted and when I try to insert data in the last row, wont let me (it clears it after I leave the cell).
UPDATE:
I've udpate the function to draw the grid
function desenhaGrid() {
$("#myGrid").load(function () {
$(function () {
$.ajax({
type: "GET",
url: '/SlickGrid/GetData',
dataType: 'json',
success: function (jsonResult) {
dataView.beginUpdate();
grid.invalidateAllRows();
dataView.setItems(jsonResult);
dataView.endUpdate();
grid.render();
}
});
});
});
}
I don't think this is a SlickGrid issue. There are all kind of problems with the javascript. For example:
why are you using $("#myGrid").ready( ? the ready event only fires when the DOM has finished loading
the entire copy operation from jsonResult to data just ends up with the same data. why not use jsonResult directly?
the section for (var i = 0; i < data.length; i++) { d["#"] = i + 1; }
runs once for each row added to data, it should just run once at the end, outside of the loop
you are subscribing to the keydown event once for each row added to the grid. you should just subscribe once. listening for an Enter key is also a very poor method of determining if a row has been entered. what if someone clicks on another row before pressing Enter?
Slickgrid is a client-side grid. This means data does not need to be persisted after every change. It's a common approach to use a 'save' button, or detect if the active row has changed.

How to catch end of html manipulations in KendoGrid after read()?

I have KendoGrid and want to detect end of all manipulations (including manipulations with html) after read(). How can I catch this event?
I have tried to use RequestEnd event with type "read", but after catching this event Kendo changes some html code in page.
Update after adding databound
I have KendoSortable, binded to KendoGrid, which contains column with positions. After position changes (onChange function), I need to block page (showLoader func) and update positions. As positions have changed, grid data (column with positions) must be reload by read(). And AFTER read() I need to unblock page by hideLoader. So, now, if I don't unbind onDataBound, my page is unblocked after remove/insert.
function onDataBound(e) {
if (ir == 0) {
updatePostion();
}
else {
hideLoader();
}
ir++;
}
function onChange(e) {
var grid = $("#TestQuestionAnswerList").data("kendoGrid");
grid.unbind("dataBound");
var newIndex = e.newIndex;
var dataItem = grid.dataSource.getByUid(e.item.data("uid"));
grid.dataSource.remove(dataItem);
grid.dataSource.insert(newIndex, dataItem);
grid.bind("dataBound", onDataBound);
showLoader();
updatePostion();
}
function updatePostion() {
if (#Model.Type == 3) {
var positions = [];
grid._data.forEach(function (entry) {
positions.push(entry.ID);
});
var dataToPost = { positions: positions, questionID: #Model.ID };
$.ajax({
url: '#Url.Action("ChangePositions", "Testing")',
type: 'POST',
data: JSON.stringify(dataToPost),
datatype: 'json',
cache: false,
contentType: "application/jsonrequest; charset=utf-8",
success: function (data) {
grid.dataSource.read();
},
error: function () {
hideLoader();
alert("error");
}
});
}
else {
grid.dataSource.read();
}
}

Jquery on click event is not working when ajax call is running at loop

I have two ajax functions that one is recursively working at loop and other is working when click event invoked. I tested both of the functions that are able to work properly. But when i start recursive function button event is not invoked.
Function that works on click event GET Content from ActionResult (MVC)
function UpdateRequests(url, state, id, cell)
{
$.ajax({
type: "GET",
url: url + id,
success: function (result) {
if (result == "OK")
{
cell.fadeOut("normal", function () {
$(this).html(state);
}).fadeIn();
}
else if(result == "DELETE" || result == "CANCEL")
{
cell.parent().fadeOut("normal", function () {
$(this).remove();
});
}
else
{
$(".modal-body").html(result);
$("#myModal").modal();
}
},
error: function () {
alert("Something went wrong");
}
});
}
Recursive function GET partial view from ActionResult (MVC)
function RefreshRequests()
{
if (isListPage())
{
var id = PageId();
var url = "/Home/List/" + id;
}
else
{
var url = "/Home/Index";
}
$.ajax({
type: "GET",
url: url,
success: function (data) {
$(".ajaxRefresh").html(data);
EditPageHeader();
},
complete: function () {
setTimeout(RefreshRequests, 2000);
}
});
}
Click event
$(".tblRequests").on("click", button, function (e) {
e.preventDefault();
var id = $(this).data("id");
var currentRow = $(this).closest("tr");
var cell = currentRow.children('td.requestState');
UpdateRequests(url, state, id, cell);
});
Main
$(document).ready(function () {
EditPageHeader();
RefreshRequests();
ButtonEvent(".btnPrepare", "/Home/Prepare/", "PREPARING");
ButtonEvent(".btnApprove", "/Home/Approve/", "APPROVED");
ButtonEvent(".btnCancel", "/Home/Cancel/", "CANCELED");
RefreshRequests();
});
Assumptions:
The Ajax Calls bring you data that end up as HTML elements in the modal body.
These new elements added above need to respond to the click event (the one that doesn't work correctly right now)
If the above 2 are true, than what is happening is you are binding events to existing elements (if any) and new elements (coming from API response) are not bound to the click event.
The statement
$(".tblRequests").on("click", button, function (e) {
...
})
needs to be executed every time new elements are added to the body. A better approach for this would be to define the event handler as an individual method and then bind it to each new element.
var clickHandler = function (e) {
e.preventDefault();
var id = $(this).data("id");
var currentRow = $(this).closest("tr");
var cell = currentRow.children('td.requestState');
UpdateRequests(url, state, id, cell);
}
// Then for each new record that you add
$(".tblRequests").on("click", button, clickHandler);
It would be helpful if you can try to explain what exactly you are trying to achieve.
Problem is that the $(this) will hold all elements of the selector. And will also now with one as it will be triggered one time and then never again. Also as can be seen from here, delegate events should be at the closest static element that will contain the dynamic elements.
function ButtonEvent(button, url, state)
{
$("body").on("click", button, function (e) {
e.preventDefault();
var button = e.target;
var id = $(button).data("id");
var currentRow = $(button).closest("tr");
var cell = currentRow.children('td.requestState');
UpdateRequests(url, state, id, cell);
});
}

Filtering HTML Table - Ajax

With my scripts below, when i start searching Facebook in my table, it appends the fetched Facebook to the table and now i have two Facebook data on the table. When i clear the search input, the table must move to the default state of having all items
Why is my script not doing such?
PS: sorry for my bad english
<script>
$(document).ready(function () {
var typingTimer;
var doneTypingInterval = 100;
$("#myInput").on('keyup', function () {
clearTimeout(typingTimer);
if ($('#myInput').val()) {
typingTimer = setTimeout(doneTyping, doneTypingInterval);
}
});
});
//user is "finished typing," do something
function doneTyping() {
var key = $('#myInput').val();
if (key.length >= 1) {
$.ajax({
url: '/customer/search/?myInput='+key,
type: 'GET',
beforeSend: function () {
$("#table").slideUp('fast');
},
success: function (data) {
console.log(data);
$("#table").slideDown('fast');
var table = $("#table tbody");
$.each(data, function(idx, elem){
table.append(
"<tr><td></td> <td>"+elem.name+"</td><td>"+elem.phone+"</td><tr>"
);
});
}
});
}
}
</script>
You added a if (key.length >= 1) condition, so if you clear the search input it won't call the ajax function again. You should just remove this condition.

is there any way to initialize details in jquery datatable?

I have a problem with jquery datatable details initialization.
I need to get table with opened details after page has loaded.
I have a following code:
function format(d) {
return d;
}
$(document).ready(function () {
$.ajax({
type: "GET",
dataType: "json",
url: "/SHOP/Promotions/GenerateDetailsToJson", //teraz w tym miejscu inicjuję dane do tabel
success: function (result) {
SetDetails(result);
},
error: function () {
alert("Wystąpił nieoczekiwany błąd");
}
})
dt = $('#table').DataTable(
{
"aoColumnDefs": [
{ 'bSortable': false, 'aTargets': [0, 6, 7] }
]
}
);
dt.on('draw', function () {
$.each(detailRows, function (i, id) {
$('#' + id + ' td:first-child').trigger('click');
});
});
$('#table').DataTable();}
var table_length = $('#table tbody tr').length; //HERE iS PROBLEM
var tr = document.getElementsByClassName("details");
for (var i = 0; i < table_length; i++) {
var row = dt.row(tr[i]);
row.child(format(details[i])).show();
}
);
The problem is in last few lines in above code.
These lines need to initialize and open all jquery datatables details but these function do not execute at time and nothing is displayed.
I have have tried to use timeout it better worked but not like as wanted and for couple of refreshing one was with no data
If You know any solution for that, please help.
You must wait for ajax request to complete.
For example:
$(document).ready(function () {
$.ajax({
//...
success: function (result) {
SetDetails(result);
process();
}
});
function process() {
var table_length = $('#table tbody tr').length;
var tr = document.getElementsByClassName("details");
for (var i = 0; i < table_length; i++) {
var row = dt.row(tr[i]);
row.child(format(details[i])).show();
}
}
});
1: try removing the ajax call before the datatable code (maybe there is some error in ajax call which leads to non working of the code below it )
2: in the ajax call , i beleive the url is wrong .
3: is there a setdetails function present , if its not present , then the code will give error
4: try run your code in firefox browser (with firebug on) , try googling about firebug if u do not know about it , but its recommended to use firebug (very helpful)
Try using $.when and .then so that you can wait for your ajax to get complete and then execute the remaining initializations as below:
$.when(
$.ajax({
....
....
})).then(function()
{
dt = $('#table').DataTable(
....
....
});
//Other initializations.
});

Categories