delete data from Bootstrap modal
Home » BLOG » Web development » How to delete data from Datatable plugin using Bootstrap modal in CodeIgniter

How to delete data from Datatable plugin using Bootstrap modal in CodeIgniter

category:  CodeIgniter, Web development
[Sassy_Social_Share] 5 min read

Recently, I wrote two posts about adding and editing the data in the Bootstrap modal in CodeIgniter. Today I will share how to delete the data using Bootstrap modal in CodeIgniter. Let’s do it.

Add new delete control in DataTable

Assume you already integrate the DataTable plugin to your template. If not, you can follow this post for integrating the DataTable plugin to your template in CodeIgniter.

Open your footer template and add the JavaScript code below. This script must be under the DataTable script.

        /**
         * DataTable initialization
         */
        $('#rep_news').DataTable({
            data: <?php echo json_encode($news) ?>,
            columns: [{
                    "data": "id"
                },
                {
                    "data": "title"
                },
                {
                    "data": "slug"
                },
                {
                    "data": "text"
                }
            ],
            columnDefs: [{
                    // # hide the first column
                    // https://datatables.net/examples/advanced_init/column_render.html                    
                    "targets": [0],
                    "visible": false
                },
                {
                    // # disable search for column number 2
                    // https://datatables.net/reference/option/columns.searchable                    
                    "targets": [3],
                    "searchable": false,
                    // # disable orderable column
                    // https://datatables.net/reference/option/columns.orderable
                    "orderable": false
                },
                {
                    // # action controller (edit,delete)
                    "targets": [4],
                    // # column rendering
                    // https://datatables.net/reference/option/columns.render
                    "render": function(data, type, row, meta) {
                        $controlls = '<button class="btn btn-sm btn-info" data-toggle="modal" data-target="#edit_news_modal" data-id="' + row.id + '" data-title="' + row.title + '" data-slug="' + row.slug + '" data-text="' + row.text + '">Edit</button>';
                        $controlls += '<button class="btn btn-sm btn-info" data-toggle="modal" data-target="#delete_news_modal" data-id="' + row.id + '" data-title="' + row.title + '" data-slug="' + row.slug + '" data-text="' + row.text + '">Delete</button>';
                        return $controlls;
                    }
                }
            ],
            // # set order descending and ascending
            // https://datatables.net/reference/option/order
            "order": [
                [1, 'desc'],
                [2, 'asc']
            ]
        });

        // ----------------------------------------------

For the code above, I add the delete button in the render option in the last column on the table. So you will see the button like this screen.

Delete button in DataTable

At the delete button, I add the data attributes which contain the data that will be deleted.

Add the delete modal

Next, we will add the delete Bootstrap modal on the template. So that when users click on the delete button, the modal will popup. Below is the delete modal code.

<!-- Deleting form modal -->
<div id="delete_news_modal" class="modal fade">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Delete News item</h4>
                <button type="button" class="close" data-dismiss="modal">×</button>
            </div>
            <div class="modal-body">

                <form method="post" id="delete_form">
                    <input type="hidden" name="id" id="id" />
                    <div class="form-group">
                        <label for="title">Title</label>
                        <input type="text" name="title" id="title" class="form-control" placeholder="Enter title" />
                    </div>
                    <div class="form-group">
                        <label for="slug">Slug</label>
                        <input type="text" name="slug" id="slug" class="form-control" placeholder="Enter slug" />
                    </div>
                    <div class="form-group">
                        <label for="text">Text</label>
                        <textarea class="form-control" name="text" id="text" cols="30" rows="10" placeholder="Enter text"></textarea>
                    </div>

                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                        <input type="submit" name="delete" id="delete" value="Delete" class="btn btn-danger" />
                    </div>
                </form>

            </div> <!-- .modal-body -->
        </div> <!-- .modal-content -->
    </div> <!-- .modal-dialog -->
</div> <!-- .modal -->

Now, when you click on the delete button, the delete modal will popup as below.

Delete modal popup

Assign the selected data on the modal

Next, we want to show the data on the modal so the users will make sure they delete the right one.

        /**
         * Assign the selected row to the Bootstrap modal
         * # Delete modal
         */
        $("#delete_news_modal").on('show.bs.modal', function(e) {
            // # relatedTarget
            // https://www.w3schools.com/jquery/event_relatedtarget.asp
            var triggerLink = $(e.relatedTarget);

            // # get the value from data attributes from the selected row.
            // https://api.jquery.com/data/
            var id = triggerLink.data("id");
            var title = triggerLink.data("title");
            var slug = triggerLink.data("slug");
            var text = triggerLink.data("text");

            // # assign the selected row value to the form
            // set the modal title
            $(this).find('.modal-title').text('Delete: ' + title);

            // # set the form
            // $(this).find(".modal-body").html("<h5>id: " + id + "</h5><p>title: " + title + "</p><p>slug: " + slug + "</p><p>text: " + text + "</p>");
            var modal_body = $(this).find(".modal-body");
            modal_body.find('#id').val(id); // this Id field doesn't need to set as disabled because we want to pass the value to $_POST.
            modal_body.find('#title').val(title).prop("disabled", true);
            modal_body.find('#slug').val(slug).prop("disabled", true);
            modal_body.find('#text').val(text).prop("disabled", true);

        });

Notice that, I set those fields on the modal as disabled. Only id field, we don’t need to set as disabled. Because we don’t need the users to edit any data on the modal. We just want to show the data that users are going to delete.

Add the form submit event

Next, we want to delete the data when the users click on the Delete button. So we want to add some code when the form is submitted. Below is the form submit code.

        /**
         * Delete a data via ajax 
         */
        $('#delete_form').on("submit", function(event) {
            event.preventDefault();

            // # form validation
            // Optional, you can use the jQuery validation plugin (https://applerinquest.com/how-to-validate-a-form-with-jquery-validation-plugin/)
            // if you don't want to do the form validation manually.

            // For the warning message, you can use the Alert message from Bootstrap if you like. I use alert() because I want to keep the post short.
            // https://getbootstrap.com/docs/4.0/components/alerts/
            var delete_modal = $('#delete_news_modal');
            var $id = delete_modal.find('#id');

            if ($id.val() != "") {

                $.ajax({
                    url: "<?php echo base_url('index.php/news/del_news_item') ?>",
                    method: "POST",
                    data: $('#delete_form').serialize(),
                    dataType: "JSON", // you must set dataType as JSON while sending the Ajax request
                    beforeSend: function() {
                        $('#delete').val("Deleting");
                    },
                    success: function(response) {
                        // # get the response from our controller
                        //console.log(response);
                        //console.log(response.del_status);
                        //console.log(response.data);

                        if (response.del_status) {
                            // reset the form
                            $('#delete_form')[0].reset();
                            $('#delete').val("Delete");

                            // hide the Bootstrap modal
                            $('#delete_news_modal').modal('hide');

                            // refresh the Datatable plugin
                            $('#rep_news').dataTable().fnDestroy();
                            $('#rep_news').DataTable({
                                data: response.data,
                                columns: [{
                                        "data": "id"
                                    },
                                    {
                                        "data": "title"
                                    },
                                    {
                                        "data": "slug"
                                    },
                                    {
                                        "data": "text"
                                    }
                                ],
                                columnDefs: [{
                                        // # hide the first column
                                        // https://datatables.net/examples/advanced_init/column_render.html                    
                                        "targets": [0],
                                        "visible": false
                                    },
                                    {
                                        // # disable search for column number 2
                                        // https://datatables.net/reference/option/columns.searchable                    
                                        "targets": [3],
                                        "searchable": false,
                                        // # disable orderable column
                                        // https://datatables.net/reference/option/columns.orderable
                                        "orderable": false
                                    },
                                    {
                                        // # action controller (edit,delete)
                                        "targets": [4],
                                        // # column rendering
                                        // https://datatables.net/reference/option/columns.render
                                        "render": function(data, type, row, meta) {
                                            $controlls = '<button class="btn btn-sm btn-info" data-toggle="modal" data-target="#edit_news_modal" data-id="' + row.id + '" data-title="' + row.title + '" data-slug="' + row.slug + '" data-text="' + row.text + '">Edit</button>';
                                            $controlls += '<button class="btn btn-sm btn-danger ml-2" data-toggle="modal" data-target="#delete_news_modal" data-id="' + row.id + '" data-title="' + row.title + '" data-slug="' + row.slug + '" data-text="' + row.text + '">Delete</button>';
                                            return $controlls;
                                        },
                                        "width": 100
                                    }
                                ],
                                // # set order descending and ascending
                                // https://datatables.net/reference/option/order
                                "order": [
                                    [1, 'desc'],
                                    [2, 'asc']
                                ]
                            });

                            // success message
                            alert('success');

                        } else {

                            alert('data is not deleted. you must check the delete script in your model.');
                        }

                    },
                    error: function(xhr, status, error) {
                        var err = eval("(" + xhr.responseText + ")");
                        alert(err.Message);
                    }
                });
            }
        });

Create del_news_item method in the controller

In the JavaScript code, we send URL via Ajax. But we don’t create this route yet. Let create it.

Open your controller and add this code.

    /**
     * Delete a data from Bootstrap modal
     */
    public function del_news_item()
    {
        $del = $this->news_model->del_news();
        $news = $this->news_model->get_news();

        // # Return our data back to ajax with Json format (json_encode)
        // you must use "echo" for returning the result you want.
        echo json_encode(
            // using the array for returning data
            array(
                'del_status' => $del,
                'data' => $news
            )
        );
    }

In this method, we call the del_news method from the model for deleting the data from the database. After that, we query all data and send them back to Ajax call. However, you don’t create the del_news method in the model yet. Let’s create it.

Add del_news method in the model

Open your model and add this code below.

    public function del_news()
    {
        $this->db->where('id', (int) $this->input->post('id'));
        return $this->db->delete('news');
    }

For the code above, we delete the data from the database. Notice that, if your id in your table is defined as integer. You must convert your post data to be integer as well.

And that’s it. You should able to delete a record from Datatable via the Bootstrap modal.