SupunSam's avatar

Laravel CRUD Delete function using Ajax

Hi Friends,

I have created a basic app with CRUD features and I've used ajax for some of the functionality since I'm using Datatables.

But unfortunately, I am unable to trigger the Delete action in this app. I have very limited knowledge with AJAX hence kindly request your help to solve this.

My Controller:


    public function getJobs()
    {
        return datatables()->of(Jobs::latest()->get())
            ->addColumn('action', function ($jobs) {
                $button = '<div class="btn-group btn-group-xs">';
                $button .= '<a href="/jobs/' . $jobs->id . '/edit" class="btn btn-primary btn-xs"><i class="fa fa-edit fa-fw"></i>&nbsp;Edit</a>';
                $button .= '<button type="button" name="delete" id="' . $jobs->id . '" class="btn btn-danger btn-xs deleteButton"><i class="fas fa-trash-alt"></i>&nbsp;Delete</button>';
                $button .= '</div>';
                return $button;
            })
            ->rawColumns(['action'])
            ->make(true);
    }

    public function destroy(Request $request)
    {
        // Jobs::find($id)->delete();
        // return redirect()->route('jobs.index')->with('success', 'Job Deleted Successfully');

        if ($request->ajax()) {
            Jobs: destroy($request->id);
        }
    }

Index.blade.php:

@section('pagejss')
<!-- DataTables -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"
    integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script src="https:////cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/rowgroup/1.1.0/js/dataTables.rowGroup.min.js"></script>
<script src="{{ asset('plugins/datatables/dataTables.bootstrap4.js') }}"></script>

<script>
    $(document).ready(function(){

    $('#jobsTable').DataTable({
        processing: true,
        serverSide: true,
        ajax: "{{ route('jobs.get') }}",
        dom: "B" + /* Buttons */
             "<'row'<'col-sm-12 col-md-6'l>" + /* Length changing input control */
              "<'col-sm-12 col-md-6'f>>" + /* Filtering Input */
                "<'row'<'col-sm-12'tr>>" + /* The Table! + Processing Display Element*/
                    "<'row'<'col-sm-12 col-md-5'i>" + /* Table Information Summary */
                        "<'col-sm-12 col-md-7'p>>", /* Pagination Control*/

        columnDefs: [
            { targets: [0,3,9,10,11,12,13,14,15,16,17], orderable: false },
            { targets: [0,3,9,10,11,12,13,14,15,16,17], searchable:false },
            { targets: [0,9,10,11,12,13,14,15,16,17,18,19,20], defaultContent: "" },
        ],

        columns:[
            /* 0 */ {data: 'action', name:'action'},
            /* 1 */ {data: 'job_no', name: 'job_no'},
            /* 2 */ {data: 'deal_no', name: 'deal_no'},
            /* 3 */ {data: 'cyc_no', name: 'cyc_no'},
            /* 4 */ {data: 'deal_name', name: 'deal_name'},
            /* 5 */ {data: 'site', name: 'site'},
            /* 6 */ {data: 'market_cat', name: 'market_cat'},
            /* 7 */ {data: 'style', name: 'style'},
            /* 8 */ {data: 'main_rend', name: 'main_rend'},
            /* 9 */ {data:  null, render: (_,__,rowData) => ['typwp_pges','typalts_pges','eowp_pges','eoalts_pges','frshtyp_pges','pdf_pges','spin_pges','qc_pges'].reduce((sum, prop) => sum+Number(rowData[prop]),0)},
            /* 10*/ {data: 'typwp_pges', name: 'typwp_pges'},
            /* 11*/ {data: 'typalts_pges', name: 'typalts_pges'},
            /* 12*/ {data: 'eowp_pges', name: 'eowp_pges'},
            /* 13*/ {data: 'eoalts_pges', name: 'eoalts_pges'},
            /* 14*/ {data: 'frshtyp_pges', name: 'frshtyp_pges'},
            /* 15*/ {data: 'pdf_pges', name: 'pdf_pges'},
            /* 16*/ {data: 'spin_pges', name: 'spin_pges'},
            /* 17*/ {data: 'qc_pges', name: 'qc_pges'},
            /* 18*/ {data: 'assigned', name: 'assigned'},
            /* 19*/ {data: 'team', name: 'team'},
            /* 20*/ {data: 'due_out', name: 'due_out'},
         ],

         rowGroup: {
         dataSrc: 'due_out'
         }
    });

    // Delete action

    $(document).on('click', '.delete', function(){
        event.preventDefault();
        var id = $(this).attr('id');
        $('#deleteModal').modal('show');

        $('#ok_button').click(function(){
            $.ajax({
            url:"/jobs/destroy/" + id,
                beforeSend:function(){

            $('#ok_button').text('Deleting...');
            },
                success:function(data)
                {
                setTimeout(function(){
                $('#deleteModal').modal('hide');
                $('#jobsTable').DataTable().ajax.reload();
                }, 2000);
                }
            })

        });

    });


});

</script>

@endsection

Everything seems fine but for some unknown reason, the delete button doesn't trigger the modal or delete actions. Kindly request your help to solve this matter

0 likes
8 replies
realrandyallen's avatar

Looks like you're targeting the delete button incorrectly, you're trying to target it by using .delete but the delete button doesn't have that class, it has the deleteButton class...try this:

 $(document).on('click', '.deleteButton', function() {
   ....

2 likes
JeffH's avatar

In response to realrandyallen he should also change his AJAX request to a delete method

$.ajax({
    url:"/jobs/destroy/" + id,
    type: 'DELETE',
});

And then make sure his route file to the destroy function is a delete route

1 like
SupunSam's avatar

This is my Route:

Route::delete('/jobs/destroy/{id}', 'JobsController@destroy');
SupunSam's avatar

My biggest problem is this button does not popup the modal. Why is that?

SupunSam's avatar

Hi Randy,

Sorry about the late reply. I messed up my code with too many JS scripts. After I've removed them now the modal box is working fine. Now I'm gonna test the ajax code.

1 like
SupunSam's avatar
SupunSam
OP
Best Answer
Level 1

After So much trouble I was able to find the issues with my code:

  1. JS rabble- I had so many unnecessary JS scripts loaded into my layout blade and my index blade as well. I loaded the only one JS min into my layout file and then it started to trigger ajax functions.

  2. Ajax function Bugs- My Ajax code had somethings missing. Eg: X-CSRF setup etc.

Below is my working code:

Controller

    public function getJobs()
    {
        return datatables()->of(Jobs::latest()->get())
            ->addColumn('action', function ($jobs) {
                $button = '<div class="btn-group btn-group-xs">';
                $button .= '<a href="/jobs/' . $jobs->id . '/edit" class="btn btn-primary btn-xs"><i class="fa fa-edit fa-fw"></i>&nbsp;Edit</a>';
                $button .= '<button type="button" name="deleteButton" id="' . $jobs->id . '" class="btn btn-danger btn-xs deleteButton"><i class="fas fa-trash-alt"></i>&nbsp;Delete</button>';
                $button .= '</div>';
                return $button;
            })
            ->rawColumns(['action'])
            ->make(true);
    }

    public function destroy($id)
    {
        Jobs::find($id)->delete();
    }

Index.blade.php



<div id="deleteModal" class="modal fade" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h2 class="modal-title">Confirmation</h2>
            </div>
            <div class="modal-body">
                <h4 align="center" style="margin:0;">Are you sure you want to remove this job?</h4>
            </div>
            <div class="modal-footer">
                <button type="button" name="ok_button" id="ok_button" class="btn btn-danger">OK</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
            </div>
        </div>
    </div>
</div>

Ajax Script

var job_id;

    // Delete action
    $(document).on('click', '.deleteButton', function(){
        job_id = $(this).attr('id');
        $('#deleteModal').modal('show');
    });

    $('#ok_button').click(function(){
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type:'DELETE',
            url:"/jobs/destroy/" + job_id,
        });
            $.ajax({
                beforeSend:function(){
                    $('#ok_button').text('Deleting...');
                },
            success:function(data)
            {
                setTimeout(function(){
                    $('#deleteModal').modal('hide');
                    $('#jobsTable').DataTable().ajax.reload();
                }, 1000);
            }
        });
    });


});

Thank you everyone for the provided suggestions and pointers. It helped a lot to debug this code.

Please or to participate in this conversation.