datatablesdatatables-1.10laravel-datatables

Mimic the ( Show All ) link in datatables.net


I have a situation where I want to get the full (data) from the backend as a CSV file. I have already prepared the backend for that, but normally the front-end state => (filters) is not in contact with the backend unless I send a request, so I managed to solve the problem by mimicking the process of showing all data but by a custom button and a GET request ( not an ajax request ). knowing that I am using serverSide: true in datatables.

I prepared the backend to receive a request like ( Show All ) but I want that link to be sent by custom button ( Export All ) not by the show process itself as by the picture down because showing all data is not practical at all.

This is the code for the custom button

    {
        text: "Export All",
        action: function (e, dt, node, config) {
            // get the backend file here
        },
    },

So, How could I send a request like the same request sent by ( Show All ) by a custom button, I prepared the server to respond by the CSV file. but I need a way to get the same link to send a get request ( not by ajax ) by the same link that Show All sends?

Datatbles buttons


Solution

  • If you are using serverSide: true that should mean you have too much data to use the default (serverSide: false) - because the browser/DataTables cannot handle the volume. For this reason I would say you should also not try to use the browser to generate a full export - it's going to be too much data (otherwise, why did you choose to use serverSide: true?).

    Instead, use a server-side export utility - not DataTables.


    But if you still want to pursuse this approach, you can build a custom button which downloads the entire data set to the DataTables (in your browser) and then exports that complete data to Excel.

    Full Disclosure:

    The following approach is inspired by the following DataTables forum post:

    Customizing the data from export buttons


    The following approach requires you to have a separate REST endpoint which delivers the entire data set as a JSON response (by contrast, the standard response should only be one page of data for the actual table data display and pagination.)

    How you set up this endpoint is up to you (in Laravel, in your case).

    Step 1: Create a custom button:

    I tested with Excel, but you can do CSV, if you prefer.

    buttons: [
      {
        extend: 'excelHtml5', // or 'csvHtml5'
        text: 'All Data to Excel', // or CSV if you prefer
        exportOptions: {
          customizeData: function (d) {
            var exportBody = getDataToExport();
            d.body.length = 0;
            d.body.push.apply(d.body, exportBody);
          }
        }
      }
    ],
    

    Step 2: The export function, used by the above button:

    function GetDataToExport() {
      var jsonResult = $.ajax({
        url: '[your_GET_EVERYTHING_url_goes_here]',
        success: function (result) {},
        async: false
      });
      var exportBody = jsonResult.responseJSON.data;
      return exportBody.map(function (el) {
        return Object.keys(el).map(function (key) { 
          return el[key] 
        });
      });
    }
    

    In the above code, my assumption is that the JSON response has the standard DataTables object structure - so, something like:

    {
      "data": [
        {
          "id": "1",
          "name": "Tiger Nixon",
          "position": "System Architect",
          "salary": "$320,800",
          "start_date": "2011/04/25",
          "office": "Edinburgh",
          "extn": "5421"
        },
        {
          "id": "2",
          "name": "Garrett Winters",
          "position": "Accountant",
          "salary": "$170,750",
          "start_date": "2011/07/25",
          "office": "Tokyo",
          "extn": "8422"
        },
        {
          "id": "3",
          "name": "Ashton Cox",
          "position": "Junior Technical Author",
          "salary": "$86,000",
          "start_date": "2009/01/12",
          "office": "San Francisco",
          "extn": "1562"
        }
      ]
    }
    

    So, it's an object, containing a data array.

    The DataTables customizeData function is what controls writing this complete JSON to the Excel file.


    Overall, your DataTables code will look something like this:

    $(document).ready(function() {
    
      $('#example').DataTable( {
        serverSide: true,
        dom: 'Brftip',
        buttons: [
          {
            extend: 'excelHtml5',
            text: 'All Data to Excel',
            exportOptions: {
              customizeData: function (d) {
                var exportBody = GetDataToExport();
                d.body.length = 0;
                d.body.push.apply(d.body, exportBody);
              }
            }
          }
        ],
    
        ajax: {
          url: "[your_SINGLE_PAGE_url_goes_here]"
        },
    
        "columns": [
          { "title": "ID", "data": "id" },
          { "title": "Name", "data": "name" },
          { "title": "Position", "data": "position" },
          { "title": "Salary", "data": "salary" },
          { "title": "Start Date", "data": "start_date" },
          { "title": "Office", "data": "office" },
          { "title": "Extn.", "data": "extn" }
        ]
    
      } );
    
    } );
    
    function GetDataToExport() {
      var jsonResult = $.ajax({
        url: '[your_GET_EVERYTHING_url_goes_here]',
        success: function (result) {},
        async: false
      });
      var exportBody = jsonResult.responseJSON.data;
      return exportBody.map(function (el) {
        return Object.keys(el).map(function (key) { 
          return el[key] 
        });
      });
    }
    

    Just to repeat my initial warning: This is probably a bad idea, if you really needed to use serverSide: true because of the volume of data you have.

    Use a server-side export tool instead - I'm sure Laravel/PHP has good support for generating Excel files.