draw() not working after table refresh with AJAX

draw() not working after table refresh with AJAX

tarudiantarudian Posts: 13Questions: 5Answers: 1

Hi,
I have a table where i used footer callback like in the example https://datatables.net/examples/advanced_init/footer_callback.html

at certain point if any data in the table is changed I refresh the table like so

 $.ajax({
                url: myurl,
                type: "GET",
                dataType: "html",
                success: function (data) {
                    $('#placeHere').html(data);
                },
            });

but than when i use a dropdwon then to search this table

myTable.columns(6).search(this.value).draw();

then during the redrawing in footercallback array variable in api() is empty.

                    "footerCallback": function (row, data, start, end, display) {
                        var api = this.api(), data;

                        // Remove the formatting to get integer data for summation
                        var intVal = function (i) {
                            return typeof i === 'string' ?
                                i.replace(/[\$,]/g, '') * 1 :
                                typeof i === 'number' ?
                                i : 0;
                        };
                        Q1 = api
                            .column(1, { page: 'current' })
                            .data()
                            .reduce(function (a, b) {
                                return intVal(a) + intVal(b);
                            }, 0);

I have been strugelling with this for a while, any idea why can't i use draw() after i use ajax to refresh data in a table ?
Would appriciate any suggestions.

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,530Questions: 1Answers: 10,473 Site admin
    Answer ✓

    Its this:

    $('#placeHere').html(data);

    You are replacing the HTML from under DataTables' feet (so to speak). It doesn't know that you've changed the HTML entirely - indeed it can't since the new HTML is a 100% new table - its a new and different DOM node, even if it has the same ID.

    You need to use the DataTables API methods to modify an existing DataTable - e.g. clear() and rows.add() in this case. Alternatively, initialise a new DataTable on your new HTML table, but that would be less efficient.

    Allan

  • tarudiantarudian Posts: 13Questions: 5Answers: 1

    Thanks allan for your anwser.

    I managed to get it working a bit differently by replacing 'this' with a proper selector to datatable
    var api = this.api(), data;
    var api = $("#myTable").dataTable().api(), data;

    Seems to be working :)

    Thanks !

This discussion has been closed.