Help with Custom Button -> pass selected column to a csv url

Help with Custom Button -> pass selected column to a csv url

dctootalldctootall Posts: 5Questions: 2Answers: 0

I'm relatively new at this, so please forgive me if I'm missing something obvious.

I've built a page that allows the user to submit a bunch of device serial numbers, and which will then query the database for all the information available within the system on those serials and display the result via datatables on the page. I've also added the ability into the page it identify and automatically select the rows in which the database doesn't contain any information on the queried serial numbers.

As the user will often then need to followup with those serials in another internal tool, I've added a copy-to-clipboard button that will pull just the serial numbers of the selected rows. This is currently working great, however like in all ventures, there's always room to improve the user experience, so I'm trying to determine if I can take those selected serials and then pass them directly into another system's API to allow the user to skip the step of copying to the clipboard and going to another page to submit that information.

Here's my current buttons code that handles the copy-to-clipboard and the filtering of just the serials:

buttons: [{ extend: 'copy', text: 'Copy Selected Serials to Clipboard', header: false, exportOptions: { columns: 1, modifier: { selected: true } } }],

I'm trying to add a button that will take the same data from above, and instead of copying it to the clients clipboard, will generate a redirect or link to another page where the data is passed as a comma seperated parameter in the URL. At this point, I dont really care if the link generation is handled all client side, or if it is handled server side thru an ajax query to a server side script that takes the array and processes it to generate the API URL (I'm honestly more comfortable with PHP than Jquery, so the server side option might be easier for me to work out). The big issue is I'm having a hard time finding information on how to pull the data from datatables and pass it on click to another ajax call or other internal process.

any help anyone could provide would be greatly appreciated.

~Daryl

This question has accepted answers - jump to:

Answers

  • kthorngrenkthorngren Posts: 20,677Questions: 26Answers: 4,839
    Answer ✓

    You can create a custom button:
    https://datatables.net/extensions/buttons/custom

    Then use something like dt.rows('.selected').data() to get the selected data which can be formatted and sent to your API.

    Kevin

  • allanallan Posts: 62,321Questions: 1Answers: 10,226 Site admin
    Answer ✓

    A small tweak I would suggest to Kevin's otherwise spot on suggestion - use dt.rows( { selected: true } ).data() (i.e. the selected selector, rather than a class selector). It should run a bit faster.

    Allan

  • dctootalldctootall Posts: 5Questions: 2Answers: 0

    Thanks for the help! This should hopefully be enough to get me started. :smiley:

  • dctootalldctootall Posts: 5Questions: 2Answers: 0
    edited February 2017

    Once again, Thank you for the help. I've managed to get my button built and it's sending the data to a server-side script which is able to strip the specific data out of the array I need and do the additional formatting needed to combine the data into a new string.

    In the name of passing it forward in case anyone else ever has a similar need, here's the code for the new custom button.

                    {
                    text: 'TestButton',
                    action: function (e, dt, node, config){
                            var ajaxData = dt.rows( {selected: true}).data().toArray();
                            $.ajax({
                                    url: 'buttonProcess.php',
                                    type: 'POST',
                                    data: JSON.stringify(ajaxData),
                                    contentType: 'application/json; charset=utf-8',
                                    dataType: 'json',
                                    async: false,
                                    success: function (response){
                                             $('.buttonResults').html(response.html);
                                            }})
                    }}
    

    and the server side:

    <?php
    
     $postInput = json_decode(file_get_contents('php://input'), true);
     $result = "";
     foreach ($postInput as $line){
            $result .= $line['SN'].',';
    };
    header('Content-Type: application/json');
    echo json_encode(['html' => $result])
    
     ?>
    
    

    I've still got some work to do to clean things up and get the rest of the functionality I'm looking for, but with these two pieces all the heavy lifting, and Datatables related work is done.

  • allanallan Posts: 62,321Questions: 1Answers: 10,226 Site admin

    Super - thanks for sharing your code with us!

    Allan

  • rf1234rf1234 Posts: 2,842Questions: 85Answers: 407

    Thanks @dctootall and @allan!

    I had a similar requirement. But I only needed to send a number of ids to the server in a simple array not all of the selected data. While this is pretty easy for single select it proved to be a bit more difficult if multiple records can be selected:

    For single select you can simply say:

    var selected = dt.row( {selected: true} );
    if (selected.any()) {
        $.ajax({
            type: "POST",
            url:  ....
            data: {
                contractId: selected.data().contract.id
            }
        });
    }
    

    This solution works for single AND for multi select:

    ....
    //custom button to put all selected contracts in to the accounting interface
    $.fn.dataTable.ext.buttons.selectedInterfaceTrue = {
        extend: 'selected',
        text: selectedInterfaceTrueLabel,
        action: function ( e, dt, button, config ) {
            var selected = dt.rows( {selected: true} ).data().toArray();
            var contractIdArray = [];
            $.each(selected, function(key, value) {
                contractIdArray.push(value.contract.id);
            })
            if ( contractIdArray.length > 0 ) {
                $.ajax({
                    type: "POST",
                    url: 'actions.php?action=acctInterfaceTrue',
                    data: {
                        contractIdArray: JSON.stringify(contractIdArray)
                    },
                    success: function () {
                        ajaxReloadTbls( [dt] );
                    }
                });
            }
        }
    };
    

    In PHP then just this to get the simple PHP array with the ids:

    .....
    $array = json_decode(filter_input(INPUT_POST,'contractIdArray'));
    
This discussion has been closed.