Deleting Rows Server Side

Deleting Rows Server Side

alenbalenb Posts: 7Questions: 3Answers: 0
edited October 2015 in Free community support

Ohrighy! I've done hours upon hours of digging, but I cannot find a single up-to-date example of this rather simple thing.

I know that rows.remove() removes the selected rows, however, from there on forward it's a mystery. I would have assumed it would send this data on remove via AJAX to the server along with the DT_RowId, but I'm not seeing this from anywhere.

Any help is highly appreciated.

JS

    var contacts = $('#contacts').DataTable({
        autoWidth: false,
        responsive: true,
        searching: false,
        lengthMenu: [ [25, 50, 100], [25, 50, 100] ],
        columnDefs: [
            { 'targets': 1, 'searchable': false },
            { 'targets': 3, 'searchable': false, 'orderable': false }
        ],
        columns: [
            { data: 'synced' },
            { data: 'type' },
            { data: 'name' },
            { data: 'checkbox' },
        ],
        serverSide: true,
        ajax: {
            url: contacts_object.ajax_url,
            data: function( data, settings ) {
                var api = new $.fn.dataTable.Api( settings );
                data.action = 'user_read_contacts';
                data.page = api.page.info().page+1;
                //alert(JSON.stringify(data));
            }
        },
        language: {
            processing: "<p class='text-center'>Loading...</p>"
        },
        processing: true
    });

    $('#contacts tbody').on('click', 'tr', function() {
        $(this).toggleClass('active');
    });

    $('#delete').on('click', function() {
        contacts.rows( $('#contacts tr.active') ).remove().draw();

// How does DataTables send row data to the server for processing?
    });

PHP

        $ccontacts = new WP_Query( $args );

        $contacts = array();
        foreach ( $ccontacts->get_posts() as $contact ) {
            $synced = get_post_meta( $contact->ID, 'synced', true );
            $type = get_post_meta( $contact->ID, 'type', true );

            $contacts[] = array(
                'DT_RowId' => $contact->ID,
                'synced' => $synced ? '<i class="fa fa-star"></i>' : '<i class="fa fa-star-o"></i>',
                'type' => $type . ' ' . $_REQUEST['pages'],
                'name' => $contact->post_title,
                'checkbox' => '<div class="checkbox"><label><input type="checkbox"></label></div>'
            );
        }

        echo json_encode(array(
            'draw' => intval( $_REQUEST['draw'] ),
            'recordsTotal' => $ccontacts->found_posts,
            'recordsFiltered' => $ccontacts->found_posts,
            'data' => $contacts
        ));

        exit;

PHP: DELETE

    // Question 1: How do I point DataTables to my delete script?
    // Question 2: How do I retrieve DT_RowId for each row that needs to be deleted from DataTables in my script?

    $rows = $_REQUEST['DT_RowId']; // would this suffice?

    foreach ( $rows as $row ) {
        // TODO: delete row
    }

    echo json_encode( array( 'Rows have been deleted successfully' ) );

    exit;

edit: added bit more info to the JS #delete on click trigger

edit: added more context just to make sure my question isn't too vague

Answers

  • tangerinetangerine Posts: 3,350Questions: 37Answers: 394

    Removing a row from the visible data, and deleting a row from a datatabase, are very different things. You would need a more advanced server-side script to send a DELETE statement to the server.

  • allanallan Posts: 61,823Questions: 1Answers: 10,129 Site admin

    Yup - delete the row from the data source (i.e. at the server) which will likely involve an Ajax request. Then draw() the table.

    Allan

  • alenbalenb Posts: 7Questions: 3Answers: 0

    I would have assumed it would send this data on remove via AJAX to the server along with the DT_RowId,

    Please read above.

    How are the rows that need to be deleted sent to the server from DataTables when rows.remove() is triggered? As I mentioned above, I would have assumed the DT_RowId of each row that needs to be deleted would be sent to the server via AJAX so the rows can be identified on the server and of course deleted.

    It's pretty straightforward that something needs to happen server side when rows.remove() is used, I'm not that green behind the ears ;)

  • allanallan Posts: 61,823Questions: 1Answers: 10,129 Site admin

    How are the rows that need to be deleted sent to the server from DataTables when rows.remove() is triggered?

    They are not. As we noted above, and as the rows().remove() documentation says, it is a client-side only function. It will remove the row from the client-side - DataTables has no inherent knowledge of your database.

    You must make an Ajax call to the server if you want to delete a call when using server-side processing.

    The key thing to keep in mind when using server-side processing is that DataTables is just a dump event and display library. All the data processing (removing, adding, editing rows) is done at the server.

    Allan

  • alenbalenb Posts: 7Questions: 3Answers: 0
    edited October 2015

    It will remove the row from the client-side

    I get that from the documentation.

    DataTables has no inherent knowledge of your database.

    I wouldn't expect this.

    it is a client-side only function

    Yep, already got that from the documentation.

    I had edited my original post to include some more information, but I guess you guys didn't quite get what I was saying.

    In any regard, I've found my answer. To anyone else out there who may get stuck on this issue and is in need of help, here's the code (I've omitted a few things which wouldn't be relevant for general use):

    JS

        $('#delete').on('click', function() {
            var selectedRows = contacts.rows( $('#contacts tr.active') ).data().to$();
    
            $.ajax({
                url: contacts_object.ajax_url,
                method: 'POST',
                data: { rows: selectedRows.toArray() },
                dataType: 'json',
                success: function( data, status, xhr ) {
                    contacts.rows( $('#contacts tr.active') ).remove().draw(false);
                }
            });
        });
    

    PHP

        $messages = array();
    
        foreach ( $_REQUEST['rows'] as $row ) {
            // DELETE IT HERE
        }
    
        echo json_encode( $messages );
    
        exit;
    
  • allanallan Posts: 61,823Questions: 1Answers: 10,129 Site admin

    Yup - that is exactly what we were trying to say. Sorry I didn't communicate it better.

    I would also note that you can just do contacts.draw(). The rows have been removed from the server-side and DataTables will make a request to get the new data from the server - which will obviously exclude the deleted rows, since they no longer exist at the server.

    Allan

This discussion has been closed.