How to process the tables rows which are dynamically added using submit button AJAX call

How to process the tables rows which are dynamically added using submit button AJAX call

anoopcranoopcr Posts: 8Questions: 2Answers: 0
edited December 2018 in Free community support

Using HTML form submit via AJAX, I am retrieving data from SQL database and adding it as my existing HTML table rows inside tbody. But datatables is not detecting the dynamically added rows. It always shows as "Showing 0 to 0 of 0 entries" eventhough I have data.

My form submit code

$(document).ready(function(e) {
    $('#analyze_submit').click(function() {

   var data = $("#analyze_options_select").val();


     $.ajax({ 

            url  :ajaxurl,
            type :'POST',
            data: { 'action': 'expense','analyze_options':data },
            success: function(data){
                $("#example tbody").html(data);
            }
        });

    }); 

});

Here is my existing table code:

<table id="example" class="grid">

                <thead>
                    <tr>
                        <th>Date</th>
                        <th>Account</th>
                        <th>Category</th>
                        <th>Description</th>
                        <th>Amount</th>
                    </tr>
            </thead>
            <tbody>

                </tbody>
                <tfoot>
            <tr>
                <th>Date</th>
                <th>Account</th>
                <th>Category</th>
                <th>Description</th>
                <th>Amount</th> 
            </tr>
        </tfoot>

            </table>

Whenever I save the webpage and reopen it in browser, it works as expected. So issue is dynamically added contents are not detecting. I am still new to jquery\javascript.
how can I resolve this issue?

This question has an accepted answers - jump to answer

Answers

  • colincolin Posts: 15,240Questions: 1Answers: 2,599

    Hi @anoopcr ,

    There's two ways you can go.

    1. tell DataTables to rescan the rows to get the updates - use rows().invalidate()
    2. get DataTables managing the Ajax request - see examples here,

    Cheers,

    Colin

  • anoopcranoopcr Posts: 8Questions: 2Answers: 0

    @colin : Thanks for the info.

    I tried to use rows().invalidate() method.

    I added below to my existing button submit after AJAX call

    $(document).ready(function(e) {
        $('#analyze_submit').click(function() {
    
       var data = $("#analyze_options_select").val();
    
    
         $.ajax({
    
                url  :ajaxurl,
                type :'POST',
                data: { 'action': 'expense','analyze_options':data },
                success: function(data){
                    $("#example tbody").html(data);
                }
            });
    
    var table = $('#example').DataTable();
    var tr = $('#example tbody tr:eq(0)');
    
    tr.find('td:eq(0)').html( 'Updated' );
    table
        .rows( tr )
        .invalidate()
        .draw();
    
        });
    
    });
    

    But its not working. To test it, I created an additional button assign below code for the button click, but this time, its clearing all the updated rows from initial AJAX call.

        $(document).ready(function(e) {
         $("#tableupdate").click(function() {
    
        var table = $('#example').DataTable();
        var tr = $('#example tbody tr:eq(0)');
    
        tr.find('td:eq(0)').html( 'Updated' );
        table
            .rows( tr )
            .invalidate()
            .draw();
    
    
            }); 
        });
    

    It looks like the rescan for new data is not working. Any thoughts on this ? (I am still a learner )

  • colincolin Posts: 15,240Questions: 1Answers: 2,599

    Hi @anoopcr ,

    The invalidate() needs to go into the Ajax success function - once you've update the HTML, otherwise the invalidate will occur before the HTML has been update.

    Cheers,

    Colin

  • anoopcranoopcr Posts: 8Questions: 2Answers: 0

    Hi @colin. Thanks for the details. I have updated the code accordingly, but its not showing the new rows now.

    $(document).ready(function(e) {
        $('#analyze_submit').click(function() {
    
       var data = $("#analyze_options_select").val();
    
         $.ajax({ 
    
                url  :ajaxurl,
                type :'POST',
                data: { 'action': 'expense','analyze_options':data },
                success: function(data){
                    $("#example tbody").html(data);
    
                    var table = $('#example').DataTable();
                    var tr = $('#example tbody tr:eq(0)');
                    tr.find('td:eq(0)').html( 'Updated' );
    
    table
        .rows( tr )
        .invalidate()
        .draw();
    
            }
            });
    
        }); 
    
    });
    

    I placed the invalidate function inside a setTimeout and found that .invalidate() removing the dynamically added contents.

  • kthorngrenkthorngren Posts: 21,351Questions: 26Answers: 4,955

    found that .invalidate() removing the dynamically added contents.

    You have .draw() which will cause the table to sort the table. Are you sure the data is removed or just sorted to a new location?

    You can test by removing .draw(). The data should remain then try a search for that data. If that works then invalidate is working.

    Kevin

  • anoopcranoopcr Posts: 8Questions: 2Answers: 0

    Hi @kthorngren. Thanks. I removed the .draw(), now new rows are showing up. But the problem is, datatable is not detecting those added rows. It always shows as > "Showing 0 to 0 of 0 entries". And when I try to do any function like sorting, filtering, all the newly added data is getting removed. Table will display message

    No data available in table

    I am unable to figure out whats going on here.

  • colincolin Posts: 15,240Questions: 1Answers: 2,599

    Hi @anoopcr ,

    We're happy to take a look, but as per the forum rules, please link to a test case - a test case that replicates the issue will ensure you'll get a quick and accurate response. Information on how to create a test case (if you aren't able to link to the page you are working on) is available here.

    Cheers,

    Colin

  • kthorngrenkthorngren Posts: 21,351Questions: 26Answers: 4,955

    One other thing you can try is to invalidate the whole table by using:

    table
        .rows(  )
        .invalidate()
        .draw();
    

    note the removal of tr from rows(). If this works then your tr selector is not selecting the correct row to invalidate.

    If you still have troubles then as Colin mentioned a test case will be needed to help debug.

    Kevin

  • anoopcranoopcr Posts: 8Questions: 2Answers: 0
    edited December 2018

    Hi @colin, @kthorngren,

    Tried the method mentioned by @kthorngren with no luck.

    Since its involved my domain sql db, I created a the issue on a test page. Here is the link

    Test Page Link

    It uses same code as mentioned above

  • kthorngrenkthorngren Posts: 21,351Questions: 26Answers: 4,955
    edited December 2018 Answer ✓

    Thanks for the example. Helps a lot. I created an example, with your data, that might help:
    http://live.datatables.net/payuqubu/1/edit

    Looks like you can add the retrieved data using rows.add(). This is a much better option than adding to HTML then invalidating. Using Datatables to update the table is the preferred method over directly updating the table followed by invalidating the Datatable data.

    However you are adding an interesting twist which is placing Updated in the first td. You can this with row().data() or cell().data(). The interesting part is you are placing it in a column with dates. When using rows.add() Datatables will set column 0's type to date format. Adding the Updated won't allow it to sort correctly. Maybe you don't need it to. Depending on how you want this to behave will determine how we need to handle it.

    You will see a few things in the example. I have it set to use rows.add() and row().data(). Note rows.add() is using $(data) to add the html based data.

    In the Datatable init you can uncomment type: 'string' to see the effect on sorting.

    You can comment out the code updating the first td and uncomment the code you are using to see the same affect.

    Kevin

  • anoopcranoopcr Posts: 8Questions: 2Answers: 0

    Hi @kthorngren, Thanks for the explanation. Its working now. And when I retrieving data from sql database, I am sorting it with the order I need, So date sorting is not really required here. I removed that part from actual code.

    Thanks once again for your all help.

This discussion has been closed.