Yuze Sun
Yuze Sun

Reputation: 63

DataTable ajax reload is not working

I have tried various ways to reload my datatable after ajax query. However, it is just not working. I tried table.ajax.reload(), table.api().ajax.reload(), switch between datatable() and DataTable(). They are just not working.

$(document).ready(function() {
    var table = $('#organizationTable').DataTable();

    $(document).on('click', '.edit-modal', function() {
        $('.modal-title').text('Edit User');
        $('#id_edit').val($(this).data('id'));
        $('#first_name_edit').val($(this).data('first_name'));
        $('#last_name_edit').val($(this).data('last_name'));
        $('#email_edit').val($(this).data('email'));
        $('#user_role_edit').val($(this).data('role_id'));
        $('#user_status_edit').val($(this).data('status_id'));
        id = $('#id_edit').val();
        $('#editModal').modal('show');
    });

    $('.modal-footer').on('click', '.edit', function() {
        if ( $( ".required" ).val().length === 0 ) {

            // Usually show some kind of error message here

            // Prevent the form from submitting
            $('#editModal').modal('show');
            event.preventDefault();
        } else {
            $.ajax({
                type: 'PUT',
                url: '/users/' + id + '/update',
                data: {
                    'id': $("#id_edit").val(),
                    'first_name': $("#first_name_edit").val(),
                    'last_name': $("#last_name_edit").val(),
                    'email': $("#email_edit").val(),
                    'role_id': $("#user_role_edit").val(),
                    'status_id': $("#user_status_edit").val()
                },
                success: function(data) {
                    console.log(data);
                    table.ajax.reload();
                }
            });
        }

    });
} );

I have a piece of initiate code in the header too.

$( document ).ready(function() {
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        dataType: 'json'
    });
});

Upvotes: 1

Views: 8142

Answers (3)

Yuze Sun
Yuze Sun

Reputation: 63

When I successfully update my form from AJax and reload the datatable, I will receive an error message saying DataTables warning: table id=organizationTable - Invalid JSON response. I think the reason is because I returned some data that doesn't match the format of my datatable. Is there a way that I can check the json format of my datatable? So, I can try to create an array that match the format for the updated user and return it as json format. Or I am looking into a wrong direction. Thank you guys.

Controller

public function update(Request $request, $id)
    {
        $user = User::find($id);

        request()->validate([
            'first_name' =>'required',
            'email' => ['required', Rule::unique('users')->ignore($user)],
        ]);

        $user->update($request->all());

        DB::table('model_has_roles')
            ->where('model_id', $user->id)
            ->update(['role_id' => $request->role_id]);

        $request->session()->flash('success', $user->first_name . ' is updated successfully.');

        return response()->json($user);
    }

DataTable View

<table id="organizationTable" class="table table-striped table-bordered">
        <thead>
        <tr>
            <th>Name</th>
            <th>Email</th>
            <th>Role Name</th>
            <th>Status</th>
            <th>Action</th>
        </tr>
        </thead>
        <tbody>
        @foreach($rainman_users as $rainman_user)
            <tr>
                <td style="vertical-align: middle">{{$rainman_user->first_name}} {{$rainman_user->last_name}}</td>
                <td style="vertical-align: middle">{{$rainman_user->email}}</td>
                <td style="vertical-align: middle">{{$rainman_user->getRoleNames()->implode(', ')}}</td>
                @if($rainman_user->status_id == 1)
                    <td class="text-success" style="text-align: center; font-style: italic; vertical-align: middle; font-weight: bold;">{{$rainman_user->userStatus->name}}</td>
                @else
                    <td class="text-danger" style="text-align: center; font-style: italic; vertical-align: middle; font-weight: bold;">{{$rainman_user->userStatus->name}}</td>
                @endif
                <td style="text-align:center;">
                    <button data-toggle="modal" data-target="#editModal" class="edit-modal btn btn-outline-primary"
                            data-id="{{$rainman_user->id}}" data-first_name="{{$rainman_user->first_name}}"
                            data-last_name="{{$rainman_user->last_name}}" data-email="{{$rainman_user->email}}"
                            data-role_id="{{$rainman_user->getRoleIds()->first()}}"
                            data-status_id="{{$rainman_user->userStatus->id}}">
                            <i class="fa fa-pencil-square-o" aria-hidden="true"></i> Detail
                    </button>
                </td>
            </tr>
        @endforeach
        </tbody>
        <tfoot>
        <tr>
            <th>Name</th>
            <th>Email</th>
            <th>Role Name</th>
            <th>Status</th>
            <th>Action</th>
        </tr>
        </tfoot>
    </table>

JavaScript

$(document).ready(function() {
    $('#organizationTable').DataTable({
    });

    $(document).on('click', '.edit-modal', function() {
        $('.modal-title').text('Edit User');
        $('#id_edit').val($(this).data('id'));
        $('#first_name_edit').val($(this).data('first_name'));
        $('#last_name_edit').val($(this).data('last_name'));
        $('#email_edit').val($(this).data('email'));
        $('#user_role_edit').val($(this).data('role_id'));
        $('#user_status_edit').val($(this).data('status_id'));
        id = $('#id_edit').val();
        $('#editModal').modal('show');
    });

    $('.modal-footer').on('click', '.edit', function() {
        $.ajax({
            type: 'PUT',
            url: '/rainman-users/' + id + '/update',
            data: {
                'id': $("#id_edit").val(),
                'first_name': $("#first_name_edit").val(),
                'last_name': $("#last_name_edit").val(),
                'email': $("#email_edit").val(),
                'role_id': $("#user_role_edit").val(),
                'status_id': $("#user_status_edit").val()
            },
            success: function(data) {
                console.log(data);
                $('#organizationTable').DataTable().ajax.reload();
            }
        });
    });
} );

Upvotes: 0

MyTwoCents
MyTwoCents

Reputation: 7624

Piece of code which you have added in Question.

Doesn't contain your ajax url or Json in Datatable you are defining.

It should be something like this

$(document).ready(function() {
    var table = $('#organizationTable').DataTable({
        ajax: "https://api.myjson.com/bins/897v1",
    });


    $('#proces_input').on('click', function() {
        table.ajax.reload(); // reload
    });
});

You can refer more examples here

Upvotes: 0

azizsagi
azizsagi

Reputation: 278

The correct way of reloading datatable is

$('#TableID').DataTable().ajax.reload();

Upvotes: 2

Related Questions