Set number of pages programmatically

Set number of pages programmatically

light2288light2288 Posts: 2Questions: 1Answers: 0

Is it possible to set the number of pages programmatically?
This is because I receive from the server just one page of records, but I want to set the real number of records (and so the real number of pages), so that the user can see the bottom pagination buttons. Using classic service side processing with Ajax request is quite problematic and not viable, and using something $('#example').DataTable().page.info().pages = numberOfPages or $('#example').DataTable().page.info().recordsTotal = numberOfRecords does not work.

This question has an accepted answers - jump to answer

Answers

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

    Hi @light2288 ,

    No, that's not possible I'm afraid. But if you use serverSide, only one page of data is returned at a time, so I suspect that may resolve your issue.

    Cheers,

    Colin

  • light2288light2288 Posts: 2Questions: 1Answers: 0

    Thanks to @colin answer, this is how i solved, I leave it here for future reference.
    1) I receive a JSON with this structure:

    const myJson = {
        myData: [ {...}, {...}, {...} ],
        totalPages: n,
        currentPage: m
    }
    

    2) Create a JSON structure from the one I receive from server this way:

    const tmpJson = {
        recordsTotal: myJson.totalPages*myPageLength, // expected by DataTables to create pagination
        recordsFiltered: myJson.totalPages*myPageLength, // expected by DataTables to create pagination
        data: myJson.myData // expected by DataTables to populate the table
        currentPage: myJson.currentPage // added by me to easily manage correct page displaying
    }
    

    This seems to work also without recordsTotal but I left it just to be sure

    3) When initializing the table, set this properties:

    $('#example').DataTable({
        ajax: function (data, callback, settings) {
            callback(
                tmpJson
            )
        }, // to show pagination together with serverSide property
        displayStart: tmpJson.currentPage*myPageLength, // page to display after page reload
        serverSide: true, // to show pagination together with ajax property
        pageLength: myPageLength
        ...
    })
    

    I don't know if it is the best way to solve it but in my specific case it works well.

This discussion has been closed.