在Laravel Ajax中获取内部错误500

时间:2017-06-28 13:51:07

标签: javascript jquery ajax laravel-5.3

我正在尝试创建一个添加表单,以便在单击提交时不会刷新页面。 AJAX似乎是这个的工具。但是,当我单击提交按钮时,我收到内部错误500。这是代码:

服务type.blade.php

{!!Form::open(['id' => 'frm-add'])!!}

    @if (count($errors) > 0)
        <div class="alert alert-danger">
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>

        <script type="text/javascript">
            $(document).ready(function () {
                $('#iconModal').modal('show');
            });
        </script>
    @endif

    <div ng-controller="serviceTypeController">
        <div class="form-group row">
            <label class="col-md-3 label-control" for="eventRegInput1">*Names</label>
            <!-- <label>[[service.typename]]</label> -->
            <div class="col-md-9">
                {!! Form::text('typeName', null, ['id' => 'name', 
                                                    'class' => 'form-control', 
                                                    'ng-model' => 'service.typename', 
                                                    'placeholder' => 'eg.Health', 
                                                    'maxlength' => '20', 'required', 
                                                    'data-toggle' => 'tooltip', 
                                                    'data-trigger' => 'focus', 
                                                    'data-placement' => 'top', 
                                                    'data-title' => 'Maximum of 20 characters', 
                                                    'minlength' => '5', 
                                                    'pattern' => '^[a-zA-Z0-9-_ ]+$']) !!}
            </div>  

        </div>

        <div class="form-group row">
            <label class="col-md-3 label-control" for="eventRegInput1">Description</label>
            <div class="col-md-9">
                {!! Form::textarea('desc', null, ['id'=>'desc', 
                                                    'class' => 'form-control', 
                                                    'ng-model' => 'service.desc', 
                                                    'maxlength' => '500',
                                                    'data-toggle' => 'tooltip',
                                                    'data-trigger' => 'focus',
                                                    'data-placement' => 'top',
                                                    'data-title' => 'Maximum of 500 characters']) !!}
            </div>  

        </div>

        <div class="form-group row last">
            <label class="col-md-3 label-control">*Status</label>
            <div class="col-md-9">
                <div class="input-group col-md-9">
                    <label class="inline custom-control custom-radio">
                        <input type="radio" id="actstat" value="active" name="stat" checked="" class="custom-control-input" ng-model="service.status">
                        <span class="custom-control-indicator"></span>
                        <span class="custom-control-description ml-0">Active</span>
                    </label>
                    <label class="inline custom-control custom-radio">
                        <input type="radio" id="actstat" value="inactive" name="stat"  class="custom-control-input" ng-model="service.status">
                        <span class="custom-control-indicator"></span>
                        <span class="custom-control-description ml-0">Inactive</span>
                    </label>
                </div>
            </div>
        </div>
    </div>

    <script>
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('[name="_token"]').val()
            }
        });

        $('#frm-add').submit(function(event) {
            $.ajax({
                url: "{{ url('/service-type/store') }}",
                type: "POST",
                data: {typeName: $("#name").val(), 
                        typeDesc: $("#desc").val(), 
                        archive: $("input[id=actstat]:checked").val(),
                        status: 1}, 
                success: function ( _response ){
                    swal("Successful", 
                            "Service type has been added!", 
                            "success");
                    console.log("Success");
                    event.preventDefault();
                }, 
                error: function(xhr, status, error) {
                    var err = xhr.responseText;
                    swal("ERROR", 
                            "Error has been caughts:\n" + err.Message, 
                            "error");
                    console.log("Error found: " + error);
                    event.preventDefault();
                }
            })
            .done(function( _data ) {
                console.log(data);
                event.preventDefault();
            });

            event.preventDefault();
        });
    </script>
    <input type="submit" class="btn btn-success" value="Add" name="btnAdd">
    <button type="button" data-dismiss="modal" class="btn btn-warning mr-1">Cancel</button>

     {!! Form::close() !!}

ServiceTypeController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use \App\Models\Servicetype;
use \Illuminate\Validation\Rule;

class ServiceTypeController extends Controller
{
   public function index() {
        $serviceTypes = ServiceType::select('typeID', 'typeName', 'typeDesc', 'status')
                                                    -> where([
                                                                ['archive', '=', 0]
                                                                ])
                                                    -> get();

        return view('service-type') -> with('serviceTypes', $serviceTypes);
    }

    public function store(Request $r) {
        try{
            $this->validate($r, [
                'typeName' => 'required|unique:servicetypes|max:20',
                ]);

            if($_POST['stat']=="active")
            {
                $stat = 1;
            }
            else if($_POST['stat']=="inactive")
            {
                $stat = 0;
            }

            $aah = ServiceType::insert(['typeName'=>trim($r->typeName),
                                                'archive'=>0,
                                                'typeDesc'=>$r->desc,
                                                'status'=>$stat]);
        } catch (Exception $exp) {
            // echo "<script>console.log('Exception Caught!\\n' + " . $exp . ");</script>";
        }


        return back();
    }

    public function getEdit(Request $r) {

        if($r->ajax())
        {
            return response(ServiceType::find($r->typeID));
        }


    }

    public function edit(Request $r)
    {

        $type = ServiceType::find($r->input('type_ID'));
        $type->typeName = $r->input('typeName');
        $type->typeDesc = $r->input('type_desc');
        $type->status = $r->input('stat');
        $type->save();
        return redirect('service-type');
    }

    public function delete(Request $r)
    {

        $type = ServiceType::find($r->input('typeID'));
        $type->archive = true;
        $type->save();
        return redirect('service-type');
    }
}

web.php

Route::get('/service-type/getEdit', 'FacilityTypeController@getEdit');
Route::post('/service-type/store', 'FacilityTypeController@store');
Route::post('/service-type/update','FacilityTypeController@edit');
Route::post('/service-type/delete','FacilityTypeController@delete');
Route::resource('/service-type', 'ServiceTypeController');

我还在主刀片模板中添加了<meta name="csrf-token" content="{{ csrf_token() }}">

我尝试将'X-CSRF-TOKEN': $('[name="_token"]').val()更改为'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')。我也尝试将<meta name="csrf-token" content="{{ csrf_token() }}">更改为<meta name="csrf-token" value="{{ csrf_token() }}">。我尝试在表单中添加{{ csrf_field() }}。我尝试在控制器内的try catch中回显异常。我尝试将两个单选按钮的ID重命名为stat,并将status: $("input[id=actstat]:checked").val()},更改为status: $("input[name=stat]:checked").val()},。捕获块没有回显(或显示警报)。我点击提交时始终会显示错误swal()console.log()。我尝试添加return false,但又一次,它没有用。我的代码出了什么问题?

0 个答案:

没有答案