duan7264 2019-07-04 14:31
浏览 171

Laravel - DataTables不会显示结果:“Ajax错误”和“500内部服务器错误”

I'm new to Laravel PHP Framework and currently continue project that was left by someone. so, because of it, i try to replicate his code to create new data list using DataTables library

what i want to achieve is simple thing, just show data list. it's using new table. I will go advance to create other feature like edit, details, action etc. but currently, just to show the data list is still failed.

Error:

DataTables warning: table id=table - Ajax error. For more information about this error, please see http://datatables.net/tn/7

This error appears, whenever i try to get data appear. enter image description here

using Chrome's developer tools not help much, i didnt get details whats wrong :

chrome developer tool

Chrome's Developer Tools, Network Tab :

enter image description here

The Tables :

enter image description here

**The View Code : **

@extends('layouts.admin.main')
@section('pageTitle', 'Sodaqoh Revenue')
@push('head')
<!-- DataTables -->
<link href="{{ asset('plugins/datatables/dataTables.bootstrap4.min.css') }}" rel="stylesheet" type="text/css">
<link href="{{ asset('plugins/datatables/buttons.bootstrap4.min.css') }}" rel="stylesheet" type="text/css">
<!-- Responsive datatable examples -->
<link href="{{ asset('plugins/datatables/responsive.bootstrap4.min.css') }}" rel="stylesheet" type="text/css">
@endpush
@section('content')
<div class="row">
    <div class="col-12">
        <div class="card m-b-20">
            <div class="card-body">
                <table id="table" class="table table-striped table-bordered dt-responsive nowrap" style="border-collapse: collapse; border-spacing: 0; width: 100%;">
                    <thead>
                        <tr>
                            <th width="5">#</th>
                            <th>{{ __('Name') }}</th>
                            <th>{{ __('Month') }}</th>
                            <th>{{ __('Year') }}</th>
                            <th>{{ __('Total') }}</th>

                        </tr>
                    </thead>
                </table>
            </div>
        </div>
    </div>
    <!-- end col -->
</div>
@endsection

@push('scripts')
<script src="{{ asset('plugins/jquery-sparkline/jquery.sparkline.min.js') }}"></script>
<script src="{{ asset('plugins/jquery-sparkline/jquery.sparkline.min.js') }}"></script>
<!-- Required datatable js -->
<script src="{{ asset('plugins/datatables/jquery.dataTables.min.js') }}"></script>
<script src="{{ asset('plugins/datatables/dataTables.bootstrap4.min.js') }}"></script>
<!-- Buttons examples -->
<script src="{{ asset('plugins/datatables/dataTables.buttons.min.js') }}"></script>
<script src="{{ asset('plugins/datatables/buttons.bootstrap4.min.js') }}"></script>
<script src="{{ asset('plugins/datatables/jszip.min.js') }}"></script>
<script src="{{ asset('plugins/datatables/pdfmake.min.js') }}"></script>
<script src="{{ asset('plugins/datatables/vfs_fonts.js') }}"></script>
<script src="{{ asset('plugins/datatables/buttons.html5.min.js') }}"></script>
<script src="{{ asset('plugins/datatables/buttons.print.min.js') }}"></script>
<script src="{{ asset('plugins/datatables/buttons.colVis.min.js') }}"></script>
<!-- Responsive examples -->
<script src="{{ asset('plugins/datatables/dataTables.responsive.min.js') }}"></script>
<script src="{{ asset('plugins/datatables/responsive.bootstrap4.min.js') }}"></script>

<script>
var oTable;
oTable = $('#table').DataTable({
    processing: true,
    serverSide: true,
    dom: 'lBfrtip',
    order:  [[ 3, "asc" ]],
    pagingType: 'full_numbers',
    buttons: [
        {
            extend: 'print',
            autoPrint: true,
            customize: function ( win ) {
                $(win.document.body)
                    .css( 'padding', '2px' )
                    .prepend(
                        '<img src="{{ asset('assets/images/logo.png') }}" style="float:right; top:0; left:0;height: 40px;right: 10px;background: #101010;padding: 8px;border-radius: 4px" /><h5 style="font-size: 9px;margin-top: 0px;"><br/><font style="font-size:14px;margin-top: 5px;margin-bottom:20px;"> @yield('pageTitle')</font><br/><br/><font style="font-size:8px;margin-top:15px;">{{date('Y-m-d h:i:s')}}</font></h5><br/><br/>'
                    );


                $(win.document.body).find( 'div' )
                    .css( {'padding': '2px', 'text-align': 'center', 'margin-top': '-50px'} )
                    .prepend(
                        ''
                    );

                $(win.document.body).find( 'table' )
                    .addClass( 'compact' )
                    .css( { 'font-size': '9px', 'padding': '2px' } );
            },
            title: '',
            orientation: 'landscape',
            exportOptions: {columns: ':visible'} ,
            text: '<i class="fa fa-print" data-toggle="tooltip" title="" data-original-title="Print"></i>',
            //className: 'btn btn-primary'
        },
        {extend: 'colvis', text: '<i class="fa fa-eye" data-toggle="tooltip" title="" data-original-title="Column visible"></i>'},
        {extend: 'csv', text: '<i class="fa fa-file-excel" data-toggle="tooltip" title="" data-original-title="Export CSV"></i>'}
    ],
    //sDom: "<'table-responsive fixed't><'row'<p i>> B",
    sPaginationType: "bootstrap",
    destroy: true,
    responsive: true,
    scrollCollapse: true,
    oLanguage: {
        "sLengthMenu": "_MENU_ ",
        "sInfo": "Showing <b>_START_ to _END_</b> of _TOTAL_ entries"
    },
    lengthMenu: [[10, 25, 50, 100], [10, 25, 50, 100]],
    ajax: {
        url: '{!! route('sodaqoh-revenue.list-index') !!}',
            data: function (d) {
                d.range = $('input[name=drange]').val();
            }
    },
    columns: [
        // { data: "rownum", name: "rownum" },
        { data: "name", name: "name" },
        { data: "month", name: "month" },
        { data: "year", name: "year" },
        { data: "total", name: "total" }
    ],
}).on( 'processing.dt', function ( e, settings, processing ) {});

$("#table_wrapper .dt-buttons").appendTo("#table_wrapper .dataTables_length");

$('#formsearch').submit(function () {
    oTable.search( $('#search-table').val() ).draw();
    return false;
} );

oTable.page.len(25).draw();

function modalDelete(id) {
    swal({
        title: "Are you sure?",
        text: "Delete this record",
        type: "warning",
        showCancelButton: !0,
        confirmButtonText: "Yes, delete it!",
        cancelButtonText: "No, cancel!",
        confirmButtonClass: "btn btn-success",
        cancelButtonClass: "btn btn-danger m-l-10",
        buttonsStyling: !1
    }).then(function() {
        deleteRecord(id);
    }, function(t) {
        "cancel" === t && swal("Cancelled", "Your data is safe :)", "error")
    })
}

function deleteRecord(id){
    $.ajax({
        url: '{{route("sodaqoh-revenue.index")}}' + "/" + id + '?' + $.param({"_token" : '{{ csrf_token() }}' }),
        type: 'DELETE',
        complete: function(data) {
            oTable.draw();
            swal("Deleted!", "Data is successfully deleted", "success");
        }
    });
}

</script>
@endpush

The Controller :

<?php

namespace App\Http\Controllers\Admin;

use App\DzikirPlaylistCategory;
use App\DzikirPlaylist;
use App\Http\Controllers\Controller;
use App\SodaqohRevenue;
use App\User;
use DB;
use Illuminate\Http\Request;
use Session;

class SodaqohRevenueController extends Controller
{
    protected $rules = [
          'id' => 'required',
          'name' => 'required',
          'month' => 'required',
          'year' => 'required',
          'total' => 'required',
          'point_total' => 'required',
          'point_rate' => 'required',
    ];

    public function index()
    {
        return view('admin.sodaqoh-revenue.index');
    }

    public function listIndex(Request $request)
    {

        DB::statement(DB::raw('set @rownum=0'));


        $model = SodaqohRevenue::all();

        $datatables = app('datatables')->of($model);

//            ->editColumn('status', function ($model) {
//                return $model->getStatusLabel();
//            })
//            ->addColumn('point', function ($model) {
//                return $model->userDetail ? $model->userDetail->point : 0;
//            })
//            ->addColumn('action', function ($model) {
//                return "<a href='". route('user-apps.show', ['id' => $model->id]) ."' class='btn btn-primary btn-sm'><i class='fa fa-eye'></i></a>";
//            });

        return $datatables->make(true);
    }
}

The Model :

<?php

namespace App;

use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Notifications\Notifiable;

class SodaqohRevenue extends BaseModel
{
    use SoftDeletes;

    const ROLE_APPS = 1;
    const ROLE_SUPERADMIN = 10;

    const STATUS_ACTIVE = 1;
    const STATUS_NEED_CONFIRMATION = 5;
    const STATUS_BLOCKED = 0;

    const REGISTER_TYPE_GENERAL = 1;
    const REGISTER_TYPE_GOOGLE = 2;
    const REGISTER_TYPE_FACEBOOK = 3;

    use Notifiable;

    protected $table = 'revenue';

    protected $fillable = [
        'id',
        'name',
        'month',
        'year',
        'total',
        'point_total',
        'point_rate',
    ];

    protected $hidden = [
        'created_by',
        'updated_by'
    ];

    public function __construct(array $attributes = array())
    {
        parent::__construct($attributes);
    }

    public function scopeRoleMobileApp($query)
    {
        return $query->where($this->table . '.role', self::ROLE_APPS);
    }
}

The Web Route :

...
    Route::get('/sodaqoh-revenue/list-index', ['as' => 'sodaqoh-revenue.list-index', 'uses' => 'Admin\\SodaqohRevenueController@listIndex']);
    Route::resource('/sodaqoh-revenue', 'Admin\\SodaqohRevenueController');
...

Laravel Log:

[2019-07-04 21:35:56] local.ERROR: Cannot use Illuminate\Notifications\Notifiable as Notifiable because the name is already in use {"userId":1,"email":"info.zipedia@gmail.com","exception":"[object] (Symfony\Component\Debug\Exception\FatalErrorException(code: 64): Cannot use Illuminate\Notifications\Notifiable as Notifiable because the name is already in use at /Users/zulkifli/zipediaPrj/webZipedia-zul-dev@github/app/SodaqohRevenue.php:7) [stacktrace]#0 {main} "}

Any Idea what's wrong ? any help is appreciated.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 DIFY API Endpoint 问题。
    • ¥20 sub地址DHCP问题
    • ¥15 delta降尺度计算的一些细节,有偿
    • ¥15 Arduino红外遥控代码有问题
    • ¥15 数值计算离散正交多项式
    • ¥30 数值计算均差系数编程
    • ¥15 redis-full-check比较 两个集群的数据出错
    • ¥15 Matlab编程问题
    • ¥15 训练的多模态特征融合模型准确度很低怎么办
    • ¥15 kylin启动报错log4j类冲突