Ajax错误在使用Laravel 5.2的Datatable时发生。

huangapple go评论88阅读模式
英文:

Ajax Error on Datatable using Laravel 5.2

问题

I have a table and showing data and using Datatables Yajra. This datatables is showing data, and all function is OK. But, sometimes error.
我有一个表格,显示数据并使用Datatables Yajra。这个Datatables正常显示数据,所有功能都正常。但是,有时会出现错误。

I am using Laravel 5.2.* and yajra datatable 6.0.*.
我正在使用Laravel 5.2.和yajra datatable 6.0.

And this is the error notification.
这是错误通知。

This is my js code
这是我的JavaScript代码

This is my slave-variable.blade.php
这是我的slave-variable.blade.php

This is my routes
这是我的路由配置

And the last is my SlaveController.php
最后是我的SlaveController.php

Then, this is the display when code run normally
然后,这是代码正常运行时的显示。

Please help me guys, thank u.
请帮助我,谢谢。

英文:

I have a table and showing data and using Datatables Yajra. This datatables is showing data, and all function is OK. But, sometimes error.
I am using Laravel 5.2.* and yajra datatable 6.0.*.

And this is the error notification.

Ajax错误在使用Laravel 5.2的Datatable时发生。

Ajax错误在使用Laravel 5.2的Datatable时发生。

This is my js code

<!-------------------------------------------->
<!-------------- SLAVE VARIABLE -------------->
<!-------------------------------------------->

<script>
$(document).ready(function() {
    
    $('#slave-variable-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: {
                url: '{{ url("/variable-list/slave-variable/data-slave-variable") }}'
            },
        columns: [
            { data: 'VARIABLE_NAME', name: 'VARIABLE_NAME' },
            { data: 'TYPE', name: 'TYPE' },
            { data: 'ADDRESS', name: 'ADDRESS' },
            { data: 'ACCESS', name: 'ACCESS' },
            { data: 'VALUE', name: 'VALUE' },
            { data: 'action', name: 'action', orderable: false, searchable: false},
            { data: 'checkbox', name: 'checkbox', orderable: false, searchable: false},
        ]
    });
    
});
</script>

<!-- DELETE DATA SLAVE_VARIABLE pada view variable-list/slave-variable -->
<script>
    $(document).on('click', '.deleteSlaveVariable', function() {
        var id = $(this).data('id-variable');
        Swal.fire({
            title: 'Are you sure to delete this variable?',
            text: "You won't be able to revert this!",
            type: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#0B5EA3',
            cancelButtonColor: '#E6222C',
            confirmButtonText: 'Delete'
        }).then((result) => {
            if(result.value) {
                $.ajax({
                    url:"/variable-list/slave-variable/delete/" + id,
                    method:"GET",
                    data:{id:id},
                    success:function(data)
                    {
                        alert(data);
                        $('#slave-variable-table').DataTable().ajax.reload();
                    }
                });
            }
        })
    });

<!-- AJAX CRUD operations -->
    // Edit a slave_variable
    $(document).on('click', '.modify-modal', function() {
        $('.modal-title').text('Modify Data');
        $('#id_variable_edit').val($(this).data('id-variable'));
        $('#id_slave_edit').val($(this).data('id-slave'));
        $('#id_slot_edit').val($(this).data('id-slot'));
        $('#variable_name_edit').val($(this).data('variable-name'));
        $('#type_edit').val($(this).data('type'));
        $('#access_edit').val($(this).data('access'));
        $('#address_edit').val($(this).data('address'));
        $('#ModifyModal').modal('show');
    });

    $(document).on('click', '#bulk_delete', function(){
        var id = [];
        if(confirm("Are you sure you want to Delete this data?"))
        {
            $('.slave_checkbox:checked').each(function(){
                id.push($(this).val());
            });
            if(id.length > 0)
            {
                $.ajax({
                    url:'{{ url("/variable-list/slave-variable/delete-all")}}',
                    method:"GET",
                    data:{id:id},
                    success:function(data)
                    {
                        alert(data);
                        $('#slave-variable-table').DataTable().ajax.reload();
                    }
                });
            }
            else
            {
                alert("Please select atleast one checkbox");
            }
        }
    });
</script>

This is my slave-variable.blade.php

<div class="card-body border-top">
                                    <h5>Slave's Variable Data</h5>
                                        <div class="table-responsive">
                                            <table class="table table-bordered table-hover" id="slave-variable-table" name="slave-variable-table">
                                                <thead class="bg-light" align="center">
                                                    <tr class="border-1">
                                                        <th class="border-1">NAME</th>
                                                        <th class="border-1">TYPE</th>
                                                        <th class="border-1">ADDRESS</th>
                                                        <th class="border-1">ACCESS</th>
                                                        <th class="border-1">VALUE</th>
                                                        <th class="border-1">ACTION</th>
                                                        <th>
                                                            <button type="button" name="bulk_delete" id="bulk_delete" class="bulk_delete btn btn-danger btn-xs">X</button>
                                                        </th>
                                                    </tr>
                                                </thead>
                                            </table>
                                        </div>
                                    </div>

This is my routes


    //Read data from table SLAVE_VARIABLES to view /variable-list/slave-variable
    Route::get('/variable-list/slave-variable', 'SlaveController@index');
    Route::get('/variable-list/slave-variable/data-slave-variable', 'SlaveController@data');

    //Update data dari table slave_variables
    Route::post('/variable-list/slave-variable/update', 'SlaveController@update');

    //Delete data dari table slave_variables
    Route::get('/variable-list/slave-variable/delete/{ID_VARIABLE}', 'SlaveController@delete');
    Route::get('/variable-list/slave-variable/delete-all', 'SlaveController@deleteAll');

And the las is my SlaveController.php

public function data()
    {
        $SLAVE_VARIABLES = SlaveModel::select('*');
        return Datatables::of($SLAVE_VARIABLES)
            ->addColumn('action', function($row){
                $btn = '<a href="javascript:void(0)" data-toggle="tooltip" 
                    data-id-variable="'.$row->ID_VARIABLE.'"
                    data-id-slave="'.$row->ID_SLAVE.'"
                    data-id-slot="'.$row->ID_SLOT.'"
                    data-variable-name="'.$row->VARIABLE_NAME.'"
                    data-type="'.$row->TYPE.'"
                    data-address="'.$row->ADDRESS.'"
                    data-access="'.$row->ACCESS.'"
                    data-original-title="Modify" class="edit btn btn-primary btn-sm modify-modal">Modify</a>';
                $btn = $btn.' <a href="javascript:void(0)" data-toggle="tooltip" data-id-variable="'.$row->ID_VARIABLE.'" data-original-title="Delete" class="btn btn-danger btn-sm deleteSlaveVariable">Delete</a>';
                return $btn;
            })
            ->addColumn('checkbox', '<input type="checkbox" name="slave_checkbox[]" class="slave_checkbox" value="{{$ID_VARIABLE}}" />')
            ->make(true);
    }
    
public function update(Request $request)
    {
        $ID_VARIABLE = $request->ID_VARIABLE;
        $ID_SLAVE = $request->ID_SLAVE;
        $ID_SLOT = $request->ID_SLOT;
        $VARIABLE_NAME = $request->VARIABLE_NAME;
        $TYPE = $request->TYPE;
        $ACCESS = $request->ACCESS;
        $ADDRESS = $request->ADDRESS;
        
        $slave_variables=SlaveModel::where('ID_VARIABLE','=',$ID_VARIABLE)
        ->update([
            'ID_SLAVE'=>$ID_SLAVE,
            'ID_SLOT' => $ID_SLOT,
            'VARIABLE_NAME' => $request->VARIABLE_NAME,
            'TYPE' => $request->TYPE,
            'ACCESS' => $request->ACCESS,
            'ADDRESS' => $ADDRESS
            ]);
            
        // alihkan halaman ke halaman /variable-list/slave-variable
        return redirect('/variable-list/slave-variable')
        ->with('update-success', 'Data has ben updated!');
    }

    /**
     * Remove the specified resource from storage.
    *
    * @param  int  $id
    * @return Response
    */

    public function delete($ID_VARIABLE)
    {
        //memilih id
        $SLAVE_VARIABLE = SlaveModel::where('ID_VARIABLE',$ID_VARIABLE);
        if($SLAVE_VARIABLE->delete())
        {
            echo 'Data Deleted';
        }
    }

    function deleteAll(Request $request)
    {
        $ID_VARIABLES = $request->input('id');
        $SLAVE_VARIABLE = SlaveModel::whereIn('ID_VARIABLE', $ID_VARIABLES);
        if($SLAVE_VARIABLE->delete())
        {
            echo 'Data Deleted';
        }
    }

Then, this is the display when code run normally
Ajax错误在使用Laravel 5.2的Datatable时发生。

Please help me guys, thank u.

答案1

得分: 1

'在你的Ajax代码中添加CSRF令牌和设置请求类型为POST'

'type': 'POST',
'data': function (d) {
    d._token = "{{ csrf_token() }}";
},
$(document).ready(function() {
    $('#slave-variable-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            'url': '{{ url("/variable-list/slave-variable/data-slave-variable") }}',
            'type': 'POST',
            'data': function (d) {
                d._token = "{{ csrf_token() }}";
            },
        },
        columns: [
            { data: 'VARIABLE_NAME', name: 'VARIABLE_NAME' },
            { data: 'TYPE', name: 'TYPE' },
            { data: 'ADDRESS', name: 'ADDRESS' },
            { data: 'ACCESS', name: 'ACCESS' },
            { data: 'VALUE', name: 'VALUE' },
            { data: 'action', name: 'action', orderable: false, searchable: false },
            { data: 'checkbox', name: 'checkbox', orderable: false, searchable: false },
        ]
    });
});
英文:

add csrf token and type post in your ajax code

'type': 'POST',
 'data': function ( d ) {
          			d._token = "{{ csrf_token() }}";

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

    $('#slave-variable-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: {
               'url' : '{{ url("/variable-list/slave-variable/data-slave-variable") }}',
            'type': 'POST',
			'data': function ( d ) {
      			d._token = "{{ csrf_token() }}";
      
            },
        columns: [
            { data: 'VARIABLE_NAME', name: 'VARIABLE_NAME' },
            { data: 'TYPE', name: 'TYPE' },
            { data: 'ADDRESS', name: 'ADDRESS' },
            { data: 'ACCESS', name: 'ACCESS' },
            { data: 'VALUE', name: 'VALUE' },
            { data: 'action', name: 'action', orderable: false, searchable: false},
            { data: 'checkbox', name: 'checkbox', orderable: false, searchable: false},
        ]
    });

});
</script>

答案2

得分: 0

我添加了 ->rawColumns(['checkbox', 'action']) 行,它之前缺失了。

英文:

modify your controller

public function data()
    {
        $SLAVE_VARIABLES = SlaveModel::select('*');
        return Datatables::of($SLAVE_VARIABLES)
            ->addColumn('action', function($row){
                $btn = '<a href="javascript:void(0)" data-toggle="tooltip" 
                    data-id-variable="'.$row->ID_VARIABLE.'"
                    data-id-slave="'.$row->ID_SLAVE.'"
                    data-id-slot="'.$row->ID_SLOT.'"
                    data-variable-name="'.$row->VARIABLE_NAME.'"
                    data-type="'.$row->TYPE.'"
                    data-address="'.$row->ADDRESS.'"
                    data-access="'.$row->ACCESS.'"
                    data-original-title="Modify" class="edit btn btn-primary btn-sm modify-modal">Modify</a>';
                $btn = $btn.' <a href="javascript:void(0)" data-toggle="tooltip" data-id-variable="'.$row->ID_VARIABLE.'" data-original-title="Delete" class="btn btn-danger btn-sm deleteSlaveVariable">Delete</a>';
                return $btn;
            })
            ->addColumn('checkbox', '<input type="checkbox" name="slave_checkbox[]" class="slave_checkbox" value="{{$ID_VARIABLE}}" />')
            ->rawColumns(['checkbox', 'action'])
            ->make(true);
    }

i added ->rawColumns(['checkbox', 'action']) line

it was missing

答案3

得分: 0

这个错误与ajax有关。通常情况下,当服务器未返回所期望的响应,即在此情况下是JSON,而是返回了HTML页面时,就会发生这种情况。请参考您上面的截图,响应返回的是找不到页面,带有httpnotfoundexception

因此,首先检查此路由/URL是否真的有效,如果有效,是否返回所需的JSON响应给datatables。

英文:

This error is related to ajax. This normally happens when the desired response is not returned from the server i.e. JSON in this case but the html page is returned instead. See your screenshot above where the response is returned page not found wiht httpnotfoundexception

So first check if this route/url is really working or not and if working then it's returning the desired response JSON to the datatables.

huangapple
  • 本文由 发表于 2020年1月3日 15:05:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/59574485.html
  • datatable
  • jquery
  • laravel
  • laravel-5
  • php

如何在 :?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定