Ad

Load DataTable Data To A Edit Modal

I am trying to create an edit function for my data table. The data table is created using Yajra Data tables. Everything working fine unless when I try to load existing data into the edit modal it fails. No error is showing but the modal does not launch. I have only included a little portion of my code here for easy reference.

Modal:

<!-- Update Status Model Box -->
    <div id="updateStatusModal" class="modal fade" role="dialog">
        <div class="modal-dialog modal-lg">
            <div class="modal-content bg-default">                
                <div class="modal-body">
                    <form class="form-horizontal" id="updateStatus">
                        @csrf
                        @method('PUT')
                        <div class="row">
                            <div class="col">
                                <div class="form-group text-center">
                                    <h6 class="font-weight-bold">Stage 1</h6>
                                    <label for="stage_1" class="switch">
                                        <input type="checkbox" class="form-control" id="stage_1">
                                        <div class="slider round"></div>
                                    </label>
                                </div>
                            </div>                            

                        </div>

                        <div class="row">                            

                            <div class="col">

                                <div class="form-group">
                                    <div class="col-md">
                                        <label for="firstname">Coding</label>
                                        <input type="text" class="form-control" id="first_name" value="" placeholder="Enter Completed Page Count">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer justify-content-between">
                    <button type="button" name="update_btn" id="update_btn" class="btn btn-outline-warning">Update</button>
                </div>
            </div>
        </div>
    </div>

jquery funtion:

// Edit action
    $(document).on('click', '.updateStatus', function(){


        $tr = $(this).closest('tr');

        var data = $tr.clidren("td").map(function(){
            return $(this).text();
        }).get();

        console.log(data);

        $('#id').val(data[0]);
        $('#job_id').val(data[2]);
        $('#stage_1').val(data[3]);
        $('#conversion').val(data[4]);     

        $('#updateStatusModal').modal('show');

    });

I tried this method I found but this is not working. Can anyone provide me any pointers here?

Ad

Answer

I've just didn't seen your front scripts (also back-end codes), but instead I can share my implementation for that you need. It works perfectly like showed in this (screenshot). Here I'll put front and back codes. There is functionality for editing existsing Datatable record, also record deletion.

FRONT

<!--HERE ATTACH NECESSARY STYLES-->

<!--VIEW end-->
<link rel="stylesheet" type="text/css" target="_blank" rel="nofollow noreferrer" href="{{ asset('css/admin/datatables.min.css') }}"/>
<table id="yajra_datatable" class="table table-bordered">
    <thead>
    <tr>
        <th>Name</th>
        <th>Options</th>
    </tr>
    </thead>
</table>
<div class="modal modal-danger fade" id="modal_delete">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">Delete Language</h4>
            </div>
            <div class="modal-body">
                <p>Are You sure You want to delete this Language?</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline pull-left" data-dismiss="modal">Cancel</button>
                <button id="delete_action" type="button" class="btn btn-outline">Submit</button>
            </div>
        </div>
    </div>
</div>
<div class="modal modal-warning fade" id="modal_edit">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">Edit Language</h4>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label for="language_name">Language Name</label>
                    <input name="language_name" id="language_name" type="text" value="" class="form-control" placeholder="Language Name">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline pull-left" data-dismiss="modal">Cancel</button>
                <button id="edit_action" type="button" class="btn btn-outline">Submit</button>
            </div>
        </div>
    </div>
</div>
<input type="hidden" id="item_id" value="0" />
<!--VIEW end-->

<!--HERE ATTACH NECESSARY SCRIPTS-->

<!--SCRIPTS start-->
<script src="{{ asset('js/admin/jquery.dataTables.min.js') }}"></script>
<script type="text/javascript">
    var YajraDataTable;
    function delete_action(item_id){
        $('#item_id').val(item_id);
    }
    function edit_action(this_el, item_id){
        $('#item_id').val(item_id);
        var tr_el = this_el.closest('tr');
        var row = YajraDataTable.row(tr_el);
        var row_data = row.data();
        $('#language_name').val(row_data.name);
    }
    function initDataTable() {
        YajraDataTable = $('#yajra_datatable').DataTable({
            "processing": true,
            "serverSide": true,
            "ajax": "{{ route('admin.book_languages.ajax') }}",
            "columns":[
                {
                    "data": "name",
                    "name": "name",
                },
                {
                    "data": "",
                    "name": ""
                },
            ],
            "autoWidth": false,
            'columnDefs': [
                {
                    'targets': -1,
                    'defaultContent': '-',
                    'searchable': false,
                    'orderable': false,
                    'width': '10%',
                    'className': 'dt-body-center',
                    'render': function (data, type, full_row, meta){
                        return '<div style="display:block">' +
                            '<button onclick="delete_action(' + full_row.id + ')" type="button" class="delete_action btn btn-danger btn-xs" data-toggle="modal" data-target="#modal_delete" style="margin:3px"><i class="fa fa-remove"></i> Delete</button>' +
                            '<button onclick="edit_action(this, ' + full_row.id + ')" type="button" class="edit_action btn btn-warning btn-xs" data-toggle="modal" data-target="#modal_edit" style="margin:3px"><i class="fa fa-edit"></i> Edit</button>' +
                            '</div>';
                    }

                }
            ],
        });
        return YajraDataTable;
    }
    $(document).ready(function() {
        var YajraDataTable = initDataTable();
        $('#delete_action').on('click', function (e) {
            e.preventDefault();
            $.ajax({
                url: "{{ route('admin.book_languages.delete') }}",
                data: {
                    'item_id': $('#item_id').val(),
                    '_token': "{{ csrf_token() }}"
                },
                type: "POST",
                success: function (data) {
                    $('#modal_delete').modal('hide');
                    YajraDataTable.ajax.reload(null, false);
                    console.log(data.message);
                }
            })
        });
        $('#edit_action').on('click', function (e) {
            e.preventDefault();
            $.ajax({
                url: "{{ route('admin.book_languages.edit') }}",
                data: {
                    'item_id': $('#item_id').val(),
                    'language_name': $('#language_name').val(),
                    '_token': "{{ csrf_token() }}"
                },
                type: "POST",
                success: function (response) {
                    $('#modal_edit').modal('hide');
                    YajraDataTable.ajax.reload(null, false);
                    console.log(data.message);
                }
            })
        });
        $('#modal_delete').on('hidden.bs.modal', function () {
            $('#item_id').val(0);
        });
        $('#modal_edit').on('hidden.bs.modal', function () {
            $('#item_id').val(0);
            $('#language_name').val("");
        });
    });
</script>
<!--SCRIPTS end-->

BACK

public function index() {
    return view('admin.book-languages.index');
}
public function ajax() {
    $items = BookLanguage::latest('id');
    return DataTables::of($items)->make(true);
}
public function delete(Request $request) {
    $item_id = $request->get('item_id');
    $item = BookLanguage::find($item_id);
    if(empty($item)) {
        return response()->json([
            'success' => false,
            'message' => 'Item not found!',
        ], 200); // 404
    } else {
        $item->delete();
        return response()->json([
            'success' => true,
            'message' => 'Item successfully deleted.',
        ], 200);
    }
}
public function update(Request $request) {
    $item_id = $request->get('item_id');
    $item = BookLanguage::find($item_id);
    if(empty($item)) {
        return response()->json([
            'success' => false,
            'message' => 'Item not found!',
        ], 404);
    } else {
        $item->name = $request->get('language_name');
        $item->save();
        return response()->json([
            'success' => true,
            'message' => 'Item successfully updated.',
        ], 200);
    }
}

ROUTES

// ...
// book_languages
    Route::group(['prefix' => 'book-languages', 'as' => 'admin.book_languages.',], function () {
        Route::get('all', '[email protected]')->name('index');
        Route::get('ajax', '[email protected]')->name('ajax');
        Route::post('update', '[email protected]')->name('edit');
        Route::post('delete', '[email protected]')->name('delete');
    });
// ...

I think this can help you and others to build wanted functionality. Here this could be also with more hint-comments, but as it not small, I can answer later via post comments.

Ad
source: stackoverflow.com
Ad