在laravel 5.3中发送验证json响应模态

时间:2016-12-13 07:30:02

标签: jquery ajax validation laravel-5

我是laravel的新手,并试图为我的模态形式使用laravel内置验证。

没有验证器,我的代码运行完美。但是当我添加验证器代码时,它会发送500内部服务器错误。我不知道这是怎么发生的,所有变量名都是正确的我认为

控制器:

public function addItem(Request $request){

    $validator = Validator::make($request->all(),[
        'code_Item'=>'required|unique|max:4',
        'name_Item'=>'required|unique|max:255',
    ]);

    if($validator->fails()){
        return \Response::json($validator);
    }
    else
    {
        $item = new kategoriBarang;
        $item->code_item = $request->code_item;
        $item->name_item = $request->name_item;
        $item->save(); 
        return \Response::json($item);         
    }   

}

路线:

Route::post('item', 'item_Ctrl@addItem');

js $ .ajax:

 $.ajax({

    type: type,
    url: my_url,
    data: formData,
    dataType: 'json',
    success: function(data) {
        console.log(data);
        /*
           success code
        */
    },
    error: function(data) {
        /*
           ihope this data contain the validation error so i can display                    it on the modal
        */
        console.log('Error:', data);
    }
});

谢谢..

查看:

@extends('layouts.mainlayout')
@section('content')
<!-- Content Wrapper. Contains page content -->
  <div class="content-wrapper">
    <!-- Content Header (Page header) -->
    <section class="content-header">
      <h1>
        item Barang
        <small>CRUD item barang</small>
      </h1>
      <ol class="breadcrumb">
        <li><a href="#"><i class="fa fa-dashboard"></i> Master Data</a></li>
        <li class="active">item barang</li>
      </ol>
    </section>

    <!-- Main content -->
    <section class="content">

      <!-- Your Page Content Here -->
      <div class="box box-primary">
        <div class="box-header with-border">
              <h3 class="box-title">item Barang</h3>
        </div>
        <div class = "box-body ">
            <div class="">
                <div class="col-sm-8 col-md-8 col-xs-8">
                    <form action ="#" method="get">
                        <div class="input-group">
                            <input type="text" name="q_item-barang" class="form-control" placeholder="Search...">
                                <span class="input-group-btn">
                                    <button type="submit" name="search" id="search-btn" class="btn btn-flat" >
                                        <i class="fa fa-search"></i>
                                    </button>
                                </span>  
                        </div>
                    </form>                
                </div>
                <div class="col-md-4 col-sm-4 col-xs-4 pull-right">
                    <div class="pull-right">
                        <button id="btn-add" class="btn btn-primary open-modal" value="">
                        <i class="fa fa-plus"></i> Add</button>
                    </div>  
                </div>
             </div>
        <br>     
        <br>     

        <div class="container col-md-12 col-sm-12">
                <table class = "table table-bordered table-striped table-fixed">
                    <tbody id="itemBarang-List">
                        <tr>
                            <th class="col-md-2">Kode</th>
                            <th class="col-md-8">Nama item</th>
                            <th class="col-md-2 col-xs-2">Operasi</th>
                        </tr>
                        @foreach($KatBarang as $item)
                        <tr id="ID{{$item->id}}">
                            <td >{{$item->code_item}}</td>
                            <td >{{$item->name_item}}</td>
                            <td >
                                <div class = "btn-group">
                                    <!--editBtn-->
                                    <button id="editBtn" class="btn btn-sm btn-warning open-modal" value="{{$item->id}}">
                                                <i class="fa fa-pencil"></i> </button>
                                    <!--deleteBtn-->
                                    <button id="deleteBtn" class="btn btn-sm btn-danger delete-task" value="{{$item->id}}">
                                                <i class="fa fa-trash"></i> </button>
                                </div>
                            </td>
                        </tr>
                        @endforeach                                            
                    </tbody>                   
                </table>
        </div>
        </div>
        <div class = "box-footer">            
        </div>
      </div>
    </section>
    <!-- /.content -->
  </div>
<!-- /.content-wrapper -->
<!--Modal window-->
<div class="modal fade" id="itemBarang-Modal" tabindex="-1" role="dialog" aria-labeledby="myModalLabel" aria-hidden="true">
    <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">x</span></button>
                <h4 class="modal-title" id="myModalLabel">item Editor</h4>
            </div>
            <div class="modal-body">
                <form id="frmitemBarang" name="frmitemBarang" class="form-horizontal container-fluid" novalidate="">
                    <div class="form-group error">
                        <div class="form-group">
                            <label class="col-sm-3 col-md-3 control-label" style="text-align: right;">Kode item</label>
                            <div class="col-sm-9 col-xs-12">
                                <input type="text" id="code-item" name="code-item" placeholder="Kode.." class = "form-control" value="">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-3 col-md-3 control-label" style="text-align: right;">Nama item</label>
                            <div class="col-sm-9 col-xs-12">
                                <input type="text" id="name-item" name="name-item" placeholder="item.." class = "form-control" value="">
                            </div>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
            <button type="button" class="btn btn-primary" id="btn-save" value="add">Save changes</button>
            <input type="hidden" name="Item_id" id="Item_id" value="0">
            </div>
        </div>
        </div>  
    </div>
</div>
@endsection

@section('script')
<meta name="_token" content="{{csrf_token()}}" />       
<script src="{{asset('js/crud-js/item-barang.js')}}"></script>
@endsection

2 个答案:

答案 0 :(得分:1)

经过一些搜索后,错误是令牌不匹配。然后我添加了

header: 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')

$.ajax内,现在可以正常使用。

然而,我仍然不清楚在每个函数中添加令牌$.ajax是否更好(每个添加/删除/更新1个)或者只是在$.ajaxsetup中声明它

答案 1 :(得分:1)

您可能遇到令牌不匹配错误,这意味着您的 CSRF令牌不存在或存在,与您当前会话的Laravel生成值不匹配。< / p>

要解决此问题,您可以使用 {{ csrf_field() }} 元素的内容在任何地方添加 <form>

要将CSRF令牌作为POST参数启用,只需在 <meta> 元素的内容中添加以下 <head> 元素:

<meta name="csrf-token" content="{{ csrf_token() }}">

然后,指示jQuery使用 $.ajaxSetup(); 自动将令牌添加到所有请求标头中,如下面的代码段所示;

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

使用后面的方案,您不再需要使用 X-CSRF-TOKEN 键值对重新定义AJAX 标题,因为您已将其全局可用;您可以简单地使用 $.ajax(); $.get(); (...阅读更多here和{{ 3}})。

以上解释的示例片段;注意:标题未定义,因为它已在全球范围内使用 $.ajaxSetup();

$.ajax({
    url: "https://www.https://stackoverflow.com/",
    type: "GET",
    dataType: "json",
    data: formData,
    success: function(data, status) {
        console.log("Data: " + data + ", Status: " + status);
    },
    error: function(data) {
        console.log("Error: " + data);
    }
});
// where formData returns your form data in the appropriate format, here, JSON.

其他有用的资源和参考here