javascriptphpjquerycodeigniterdatatables

Delete Field in Datatable with ajax in Codeiginiter without refreshing page


I want to delete some field in datatable using 'a' tag as a button. If that button is pressed, it will delete field in my database using ajax without refreshing page but if i click the button, it doesn't do anything. I am weak in JS or jQuery, I hope you guys will help me, thanks.

This is my JS

$('#delete-agenda').click(function(e) {
    e.preventDefault();
    var data = {};
    data['id_itenerary'] = $(this).attr('value');
    $.ajax({
        url: 'http://localhost/pandansari/admin/single_trip/delete_agenda',
        type: 'post',
        data: data
    });
});

This is my 'a' tag

<a id="delete-agenda" class="btn btn-sm btn-danger" value="<?php echo $agenda['id_itenerary'] ?>">Delete</a>

This is my controller function

public function delete_agenda() {
    $id_itenerary = $this->input->post('id_itenerary');
    $this->agenda_model->delete_agenda($id_itenerary);
}

This is my model function

public function delete_agenda($id_itenerary) {
    $this->db->where('id_itenerary', $id_itenerary);
    $this->db->delete('tb_itenerary');
}

Solution

  • Try this

    HTML:

    <a id="delete-agenda" href="#" class="btn btn-sm btn-danger" data-id="<?php echo $agenda['id_itenerary'] ?>">Delete</a>
    

    JS:

    $(document).ready(function() {
        $('#delete-agenda').click(function(e){
            e.preventDefault();
            var id = $(this).attr('data-id');
            $.ajax({
                url: 'http://localhost/pandansari/admin/single_trip/delete_agenda',
                type: 'post',
                data: { 'id_itenerary' : id }
            });
        });
    });
    

    You will still have to remove the datatable entry from the table; otherwise the change will only be apparent on refresh/reload.