Return IDs of selected rows to server

Return IDs of selected rows to server

muuuchomuuucho Posts: 7Questions: 2Answers: 0

I use Datatables with MySql. In my index view, I display all posts from a table and I can start to filter/sort and I get a remaining selection of rows left.

In this view, I want a button - "Post selection" - that sends the ID's of all selected rows back to the server.

Let's say i have a table cars:

id
brand
color

populated like this:

1 Mazda Brown
2 Buick Red
3 Ford Red

Then I filter out all red cars and hit the button "Post selection"
I now want to recieve an array like: {2,3} in my controller

How can I achieve this?

Answers

  • kthorngrenkthorngren Posts: 21,231Questions: 26Answers: 4,929

    First you would tell Datatables which column you want to use for the row ID using rowId. In your button click event you would use rows().ids() to get the row IDs and use the toArray() API to place them in an array. In order to get the IDs of the rows in the search result you would use the selector-modifier of {search: 'applied'}.

    Here is a simple example based on your example data:
    http://live.datatables.net/jehiqafu/1/edit

    Kevin

  • muuuchomuuucho Posts: 7Questions: 2Answers: 0

    Thanks a lot! It looks great.
    After the click, I like to do a redirect to a PHP controller that saves the array to a database and then display another page. Something like:

    $('button').on('click', function () {

            var ids = table.rows({search: 'applied'}).ids().toArray();
            console.log(ids);
    
            // Create object containing the array of IDs
            var dataObject = { data: ids };
    
            // Send object via POST request to server
            $.ajax({
                type: "POST",
                data: dataObject,
                url: "<?=base_url('panel/another_page');?>",
                success: function(msg) {
                    console.log("Success: " + msg);
                    window.location.href = "<?=base_url('panel/another_page');?>";
                },
                error: function(err) {
                    console.log("Error sending data to server: " + err);
                }
            });
        })
    

    The PHP Controller:
    function another_page()
    {
    $array = $_POST(ids);
    // Do whatever with the array...
    $this->load->view('another_page');
    }

    However, this doesn't work.

  • kthorngrenkthorngren Posts: 21,231Questions: 26Answers: 4,929

    However, this doesn't work.

    What is happening?

    Do you get errors in your browsers console?

    Are you getting the IDs correctly?

    Kevin

This discussion has been closed.