Is there a way to email a datatable?

Is there a way to email a datatable?

mRendermRender Posts: 151Questions: 26Answers: 13

Possibly something like one of the table tools buttons that you click, a text box pops up and you put an e-mail address in there and hit send.

If not, what's the best way of going about emailing my tables?

This question has an accepted answers - jump to answer

Answers

  • anaganag Posts: 48Questions: 2Answers: 7

    Your question is not very clear.

    First where are you storing the email address? You say you want to send it to datatables, but if it's only sent client side, when the user refreshes it'll be gone, since it's not stored anywhere.

    Next where are you loading data from into the table? Is it getting it from an HTML table client side? Or are you using server side processing, or AJAX to load the data?

    You can use jQuery to open a modal or dialog with a form input. From that form you can send the email address to your database with AJAX, then reload your table.

    Since you've given no example of how your table is initialized, no live demo, or code. You should really move on to Google and search for some examples of posting forms with AJAX. Come back edit your question and show what you have tried.

  • mRendermRender Posts: 151Questions: 26Answers: 13

    It was just kind of a general question asking if there was already a way to e-mail datatables in any way. If you could help me out and point me in a general direction I'd really be appreciative of that. I've included my code below.

    $(document).ready(function() {
        editor = new $.fn.dataTable.Editor( {
            processing: true,
            seriverSide: true,
            ajax: "DataTables-1.10.0/extensions/Editor-1.3.1/examples/php/pexpenses.php?ID=<? echo $ID?>",
            table: "#pexpenses",
            fields: [  {
                    label: "Type:",
                    name: "tbl_pexpenses.type",
                    type: "select"
                }, {
                    label: "Cost:",
                    name:  "tbl_pexpenses.cost"
                }, {
                    label: "Quantity:",
                    name:  "tbl_pexpenses.quantity"
                }, {
                    label: "Description:",
                    name:  "tbl_pexpenses.description"
                }
            ]
        } );
        
        
        $('#pexpenses').DataTable( {
            dom: "Tfrtip",
            pageLength: -1,
            type: 'POST',
            paging: false,
            info: false,
            idSrc: "tbl_pexpenses.PEID",
            ajax: "DataTables-1.10.0/extensions/Editor-1.3.1/examples/php/pexpenses.php?ID=<? echo $ID ?>",
            columns: [
                { data: "tbl_types.type_desc" },
                { data: "tbl_pexpenses.description" },
                { data: "tbl_pexpenses.cost" },
                { data: "tbl_pexpenses.quantity" },
                { data: null,
                        render: function ( data, type, row ) {
                    return (data.tbl_pexpenses.cost*data.tbl_pexpenses.quantity);
                     } }
            ],
                tableTools: {
                sRowSelect: "os",
                sSwfPath: "../DataTables-1.10.0/extensions/TableTools/swf/copy_csv_xls_pdf.swf",
                aButtons: [
                    { sExtends: "editor_create", editor: editor },
                    { sExtends: "editor_edit",   editor: editor },
                    { sExtends: "editor_remove", editor: editor },
                    "print",
                    {
                        "sExtends":    "collection",
                        "sButtonText": "Save",
                        "aButtons":    [ "csv", "xls", "pdf" ]}
                    
                ]
            },
            "order": [[ 0, 'asc' ]],
            "drawCallback": function ( settings ) {
                var api = this.api();
                var rows = api.rows( {page:'current'} ).nodes();
                var last=null;
     
                api.column(0, {page:'current'} ).data().each( function ( group, i ) {
                    if ( last !== group ) {
                        $(rows).eq( i ).before(
                            '<tr class="grouping" ><td colspan="5">'+group+'</td></tr>'
                        );
     
                        last = group;
                    }
                    } );
            },  
            initComplete: function ( settings, json ) {
                editor.field( 'tbl_pexpenses.type' ).update( json.tbl_types );
            },
            footerCallback: function ( row, data, start, end, display ) {
                var api = this.api(), data;
     
                // Remove the formatting to get integer data for summation
                var intVal = function ( i ) {
                    return typeof i === 'string' ?
                        i.replace(/[\$,]/g, '')*1 :
                        typeof i === 'number' ?
                            i : 0;
                };
     
                // Total over all pages
                data = api.column( 4 ).cache('search');
                total = data.length ?
                    data.reduce( function (a, b) {
                            return intVal(a) + intVal(b);
                    } ) :
                    0;
     
                // Update footer
                $( api.column( 4 ).footer() ).html(
                    '$'+ total
                );
            }
            
            
        } );
    } );
        
        
    // Order by the grouping
        $('#example tbody').on( 'click', 'tr.group', function () {
            var currentOrder = table.order()[0];
            if ( currentOrder[0] === 0 && currentOrder[0] === 'asc' ) {
                table.order( [ 0, 'desc' ] ).draw();
            }
            else {
                table.order( [ 0, 'asc' ] ).draw();
            }
        } );    
    
  • anaganag Posts: 48Questions: 2Answers: 7

    To try and answer your questions

    "something like one of the table tools buttons that you click"

    You can create an HTML button and place it above your table, or next to the table tools. Or even inside with them using jQuery. The simplest thing to do is create an HTML button. Give it a unique class.

    "a text box pops up"

    One method is with Bootstraps Modal. Clicking a button popups open a modal, which can contain a text input field and submit button where an email address is entered and submitted.
    http://getbootstrap.com/javascript/#modals

    "you put an e-mail address in there and hit send."

    Bind a jQuery event to the button, on click submit the form with AJAX to your server and process the email as needed. ie; insert it to your database. If you're not displaying the email address in the table there's no need to redraw the table.

  • mRendermRender Posts: 151Questions: 26Answers: 13
    edited July 2014

    Okay so here is my updated code with what I've been working with:

    This is the code that I use to populate the e-mail button. It works and correctly calls the appropriate function.

    aButtons: [
                    { sExtends: "editor_create", editor: editor },
                    { sExtends: "editor_edit",   editor: editor },
                    { sExtends: "editor_remove", editor: editor },
                    {
                        sExtends: "ajax",
                        sButtonText: "Email",
                        fnClick: function ( nButton, oConfig, oFlash ) {
                        sendemail();
                        }},
                    "print",
                    {
                        "sExtends":    "collection",
                        "sButtonText": "Save",
                        "aButtons":    [ "csv", "xls", "pdf"]}
                ]
            },
    

    Here is my sendemail function. The variable thehtml has the proper rows in it when I write it, but not when I e-mail it later.

    var thehtml = "";
        $(document).ready(function() {
    $('#expenses').on( 'draw.dt', function () {
      thehtml = $( "#expensesdiv" ).html();
    
    });
    });
    
    function sendemail() {
        if (window.XMLHttpRequest)
        {// code for IE7+, Firefox, Chrome, Opera, Safari
          xmlhttp=new XMLHttpRequest();
         }
        else
         {// code for IE6, IE5
          xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
         }
        xmlhttp.onreadystatechange=function()
        {
          if (xmlhttp.readyState==4 && xmlhttp.status==200)
            {
                
                var response = xmlhttp.responseText;
                response = response.replace(/^\s+|\s+$/g,'')
                
                if(response == 'error'){
                    alert('Email Not Sent');
                    }
                
                else {
                    alert('Email Sent');
                }
            }
        }   
        xmlhttp.open("GET","sendemail.php?TID=1&emailbody="+thehtml);
        xmlhttp.send();
    }
    

    Here is my code when I e-mail it:
    ```
    $body = '
    <html>
    <head></head>
    <body>

        <p>'.$emailbody.'</p>
    </body>
    

    </html>
    ';

            $to = 'me@gmail.com';
            $subject = 'Test Email';
            $headers  = 'MIME-Version: 1.0' . "\r\n";
            $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
    
    
            mail($to, $subject, $body,  $headers, '-fme@gmail.com');
    

    if ($headers = ""){
    echo "error";
    }
    else{
    echo "okay";
    }

    <?php > ``` ?>

    The email sends, the issue is that the e-mail doesn't have the datatable's html in it.

  • anaganag Posts: 48Questions: 2Answers: 7

    Use console.log(thehtml) to debug, do you see the div's html in your console debugger?

    $('#expenses').on( 'draw.dt', function () {
      thehtml = $( "#expensesdiv" ).html();
      console.log(thehtml);
    });
    
  • anaganag Posts: 48Questions: 2Answers: 7
    Answer ✓

    Also in sendemail.php if you echo the variable you're sending. In developer tool on the Network tab select that file after you make the AJAX request, you can then view the response and see if it's been sent correctly and received.

  • mRendermRender Posts: 151Questions: 26Answers: 13

    Alright, here's an update to what I've done to get it to work. This code e-mails the html of the datatable.

    SENDEMAIL.JS

    function sendemail() {
        var pid = $("#elempid").val();
        var dt = $('#pexpenses').dataTable();
        var footer = dt.api().columns().footer()[4].innerHTML;
        var rows = dt.fnGetNodes();
        var rowStr = "";
        for(var i = 0; i < rows.length; i++){
            rowStr += rows[i].innerHTML;
            if(i < rows.length - 1){
                rowStr += ",";
            }
        }
        $.ajax({
            url: "sendemail.php",
            type: "POST",
            data: "PID=" + pid + "&emailbody=" + rowStr + "&emailfoot=" + footer,
            success:function(data){
                if(data == "okay"){
                    alert("Email Sent!");
                }
                else{
                    alert("Error!");
                    console.log("Error Data Received:" + data);
                }
            }
        });
    }
    

    SENDEMAIL.PHP

    $PID = $_POST['PID'];
    $emailbody = $_POST['emailbody'];
    $emailfoot = $_POST['emailfoot'];
    
    $emailbodyarray = explode(",", $emailbody);
    $body = "";
    foreach($emailbodyarray as $em){
        $body .= "<tr>";
        $body .= $em;
        $body .= "</tr>";
    }
                
    $body =  "
            <table>
                <thead>
                    <tr role=\"row\"><th class=\"sorting\" tabindex=\"0\" aria-controls=\"pexpenses\" rowspan=\"1\" colspan=\"1\" aria-label=\"Type: activate to sort column ascending\" style=\"width: 235px;\">Type</th><th class=\"sorting_asc\" tabindex=\"0\" aria-controls=\"pexpenses\" rowspan=\"1\" colspan=\"1\" aria-label=\"Description: activate to sort column ascending\" style=\"width: 425px;\" aria-sort=\"ascending\">Description</th><th class=\"sorting\" tabindex=\"0\" aria-controls=\"pexpenses\" rowspan=\"1\" colspan=\"1\" aria-label=\"Cost: activate to sort column ascending\" style=\"width: 152px;\">Cost</th><th class=\"sorting\" tabindex=\"0\" aria-controls=\"pexpenses\" rowspan=\"1\" colspan=\"1\" aria-label=\"Quantity: activate to sort column ascending\" style=\"width: 239px;\">Quantity</th><th class=\"sorting\" tabindex=\"0\" aria-controls=\"pexpenses\" rowspan=\"1\" colspan=\"1\" aria-label=\"Item Total: activate to sort column ascending\" style=\"width: 274px;\">Item Total</th></tr>
                <thead>
                <tbody>
                    {$body}
                </tbody>
                <tfoot>
                    <tr></tr>
                    <tr></tr>
                    <tr></tr>
                    <tr>TOTAL: {$emailfoot}</tr>
                </tfoot>
            </table>
    ";
            
                $to = 'myemail@email.com';
                $subject = 'SUBJECT';
                $headers  = 'MIME-Version: 1.0' . "\r\n";
                $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
                
                
                mail($to, $subject, $body,  $headers, '-youremail@email.com');
    
    if ($headers = ""){
        die("error");
    }
    else{
         die("okay");
    }
    
This discussion has been closed.