Store table data in browser

Store table data in browser

kevintivolikevintivoli Posts: 18Questions: 4Answers: 0

Hello,

I am adding data to table using row.add, which is working fine, but the data disappears when page is refreshed. Is there a way to store this data in cache or something until a POST method is called ?

Thanks

This question has an accepted answers - jump to answer

Answers

  • colincolin Posts: 15,146Questions: 1Answers: 2,586

    You could usestateSave to store that optional data. In this example, it's showing how to store selected rows. You could modify that to store created rows, which you then re-add on table reload.

    Colin

  • kevintivolikevintivoli Posts: 18Questions: 4Answers: 0

    Colin, Thanks for your response.

    I'm very new to DataTables and JavaScript.

    I already have StateSaveenabled. I have tried your suggestions stateSaveParams, stateLoadParams and initComplete, but couldn't get it work. Not sure where i am going wrong. I may be completely using it in incorrect order. Would you please provide and example based on my scenario.

    I am adding data from a product table to cart table. Both are datatables.

    Here is my code. Would you please correct where i should include your suggestions ?

    <script>
            // WSCart Table 
        $(document).ready(function () {
            var wscart_table = $('#wscarttable').DataTable({
                "dom": 'lrtip',
                "paging": false,
                "info": false,
                StateSave: true,
                columns: [{data: 'idnum'}, {data: 'productid'},
                {
                mRender: function (data, type, row) {
                      return '<input type="number" value="1" id="qty-btn" min="0" max="100" step="1"/>'
                    }}
                ],
            });
    
            // Add to Cart from Product Table
            $('#productstable tbody').on('click', '#addtowscart', function (e) {
                e.preventDefault();
                var products_table = $('#productstable').DataTable();
                var idx = products_table.row($(this).parents('tr')).data();
    
                wscart_table.row.add( {
                    "idnum": idx.pk,
                    "productid": idx.fields.product_id,
                } ).draw();
            });
        });
    </script>
    
  • colincolin Posts: 15,146Questions: 1Answers: 2,586

    I'm not seeing that stateLoadParams in your code, so I can't comment on what you've done. Can you show me the code you're trying to get working, please. One thing to note, is it's stateSave - case matter.

    Colin

  • kevintivolikevintivoli Posts: 18Questions: 4Answers: 0

    Colin,

    This is what i tried. Not sure, if i am using the stateSaveParams, stateLoadParamsand initCompletein the correct place.

    Basically, i need to add products from products DataTable to cart DataTable and save the state of cart DataTable .

    <script>
        // WSCart Table
        $(document).ready(function () {
            var saveddata;
            var products_table = $('#productstable').DataTable();
            var wscart_table = $('#wscarttable').DataTable({
                "dom": 'lrtip',
                "paging": false,
                "info": false,
                stateSave : true,
                select : true,
                'stateSaveParams': function(settings, data) {
                  },
                  'stateLoadParams': function(settings, data) {
                    saveddata = data.saveddata;
                  },
                  'initComplete': function() {
                    this.api().rows(saveddata);
                    this.api().state.save(saveddata);
                  },
                columns: [{data: 'idnum'}, {data: 'productid'},
                {
                mRender: function (data, type, row) {
                      return '<input type="number" value="1" id="qtybtn" min="0" max="100" step="1"/>'
                    }}
                ],
            });
    
            // Add to Cart from Product Table
            $('#productstable tbody').on('click', '#addtowscart', function (e) {
                e.preventDefault();
                var table = $('#productstable').DataTable();
                var idx = table.row($(this).parents('tr')).data();
                wscart_table.row.add( {
                    "idnum": idx.pk,
                    "productid": idx.fields.product_id,
                } ).draw();
    
                saveddata = wscart_table.rows().data();
                wscart_table.state.save(saveddata);
            });
        });
    </script>
    
  • colincolin Posts: 15,146Questions: 1Answers: 2,586
    Answer ✓

    That's heading in the right direction. You need to hold onto the list of added rows, to ensure they're getting saved. This example here is doing just that. The Add row button is creating new rows, which are then stored in the stateSave data.

    Hope that helps,

    Colin

  • kevintivolikevintivoli Posts: 18Questions: 4Answers: 0

    Thank you so much @colin , i followed the example you provide and it worked like a charm !! Appreciate your help.

    I have one last last question. In order to clear the state of the table without refreshing the whole page. This is what i am doing, is this correct ?

    $('#empty-cart').click(function () {
                wscart_table.clear().draw();
                wscart_table.state.clear();
     });
    

    For others :- Below is my code that worked based on @colin 's suggestion.

    <script>
    $(document).ready(function () {
        var addedRows;
        var products_table = $('#productstable').DataTable();
        var wscart_table = $('#wscarttable').DataTable({
            "dom": 'lrtip',
            "paging": false,
            "info": false,
            stateSave: true,
            'stateSaveParams': function (settings, data) {
                data.added = addedRows;
            },
            'stateLoadParams': function (settings, data) {
                addedRows = data.added;
                if (addedRows === undefined) {
                    addedRows = [];
                }
            },
            'initComplete': function () {
                this.api().rows.add(addedRows).draw();
                this.api().state.save();
            },
    
            columns: [{ data: 'idnum' }, { data: 'productid' },
            {
                mRender: function (data, type, row) {
                    return '<input type="number" value="1" id="qtybtn" min="0" max="100" step="1"/>'
                }
            }
            ],
        });
    
    
        $('#productstable tbody').on('click', '#addtowscart', function (e) {
            e.preventDefault();
            var idx = products_table.row($(this).parents('tr')).data();
    
            data = ({
                "idnum": idx.pk,
                "productid": idx.fields.product_id,
            });
            addedRows.push(data);
            wscart_table.row.add(data).draw(false);
            wscart_table.state.save();
        });
    
    
        $('#empty-cart').click(function () {
            wscart_table.clear().draw();
            wscart_table.state.clear();
        });
    
    });
    

    </script>

  • colincolin Posts: 15,146Questions: 1Answers: 2,586

    You're welcome, glad it's all working. And yep, that looks correct, but given your question, I'm guessing there's a problem? If there is, please can you update my test case to demonstrate it, that way it'll be clearer to see.

    Colin

  • kevintivolikevintivoli Posts: 18Questions: 4Answers: 0

    @colin , You are right, there is a weird problem.

    It seems to work the first time you click on "Empty Table" and as long as you don't refresh the page.

    And when you refresh the page, the "Add Row" stops working, it doesn't add any items to the table anymore.

    Then, It starts working again, if you refresh the page one more time.

    I have updated your test case to demonstrate it here

  • kevintivolikevintivoli Posts: 18Questions: 4Answers: 0

    @colin - To precisely recreate the issue.

    Add a couple of rows by clicking on "Add Row" button, then click on "Empty Table" to remove all rows from the table. Now, refresh the page and try to click on "Add Row". It stops working, until you refresh the whole page again.

  • colincolin Posts: 15,146Questions: 1Answers: 2,586

    If you move the state.clear() before the clear() then it works - I'm not entirely sure why, but if that works for you, then I'm happy :)

    Colin

  • kevintivolikevintivoli Posts: 18Questions: 4Answers: 0

    @colin

    Unfortunalty, moving the state.clear()before the clear() is not working for me. I have createed a new thread for this issue here.

    Would you please take a look when you have a moment. I think i am close to achieving what i am looking for. Your help is really appreciated.

  • rf1234rf1234 Posts: 2,808Questions: 85Answers: 406
    edited June 2020

    isn't this issue now resolved here in the new thread you mention above?
    https://datatables.net/forums/discussion/62458

    and with this example:
    http://live.datatables.net/fexiqido/1/edit

This discussion has been closed.