Best way to handle ajax changing/adding rows?
Best way to handle ajax changing/adding rows?
Hi all,
My tables are made in PHP and returned via Ajax. However, I also add or replace rows without necessarily reloading the whole table from the server. When this happens, DataTable sorting can cause rows that were updated to revert to their previous state, though the underlying database of which the table is a reflection is, of course, not affected. I'm guessing this is simply because DT doesn't know about the changes in the DOM.
My question is pretty simple. What's the best way to give DT the latest update to the table, short of calling ".dataTable" on the table again? Or is that the solution? It seems to me, an inexperienced web developer making small, internal-use-only pages, that there'd be a different way. But I don't know. Performance isn't a problem, but I wonder if doing this would cause the user's position to change. Any ideas? Thanks.
Replies
How are you doing this?
If you are updating the table using something other than Datatables APIs then you can use something like
rows().invalidate()
to have Datatables refresh its information.Kevin
Thank you, this looks like exactly what I need. I'll try it tomorrow morning.
My PHP page, the backend to the Ajex, can generate the full table of data. It can also generate just one row, returning that row and nothing else. When the user clicks a checkbox in any row, an on("click") function bound to the box fires. The ID of the row (matching the ID of the row in the database the table represents) is given to the Ajex file, as is a parameter specifying that I want only the row for this ID, not the full table. The backend file uses that ID to update the database, then get the updated values and return them as a row. On success, I find the row in the table and replace it with the one I got in the Ajex call. It sounds like all I need to do is add $(myRow).invalidate() to my Ajax success function and all will work as I want it too.
For reloading the whole table when it's AJAX I would recommend don't use .datatable again, use
yourTable.ajax.reload()
For updating a single row, I think your best bet is to just take the data that was returned from the server (which is supposed to be the new row data) and use
yourTable.row("some selector").data({new data})
. I think that would be the minimum effort way, because you have everything in place from the sounds of it.The only problem is that I'm not using DataTable's ajax functionality. I couldn't get it to work right, so it seemed easier to just leave my existing code in place, calling .dataTable() on my generated table after it had been retrieved. Is there a reload method for a non-ajax table that I didn't notice?
Simply call
clear()
and thenrows.add()
in sequence. That's basically allajax.reload()
does, just with an Ajax call as well.Allan