簡體   English   中英

422(使用ajax提交表單時發生不可處理的實體錯誤

[英]422 (Unprocessable Entity error when submitting form with ajax

我試圖使用模式提交表單,但出現此錯誤。 422(不可處理實體)。 在我的菜單模型中,我使用受保護的$ table ='menu'指定了我的表名$ menu;

<script type="text/javascript">

$(document).ready(function(){

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

我的讀取功能完全正常,但添加無效

        function load(){
        $.get('dash',function(data){
        $.each(data,function(key,val){
            $('#data')
            .append("<tr>"+
                    "<td>"+val.Item_Code+"</td>"+
                    "<td>"+val.Name+"</td>"+
                    "<td>"+val.Printer+"</td>"+
                    "<td>"+val.Category+"</td>"+
                    "<td>"+val.Price+"</td>"+
                    "<td>"+val.Stocks+"</td>"+
                    "<td>"+val.Image+"</td>"+
                    "<td>"+
                    "<button type='button' class='btn btn-outline-success'>
                     <i class='fa fa-clipboard'></i> &nbsp; Edit</button>"+
                    "<button type='button' class='btn btn-outline-danger'><i 
                     class='fa fa-trash'></i> &nbsp; Delete</button>"+
                    "</td>"+
                    "</tr>");
                     });
                   });
                  }

我的添加函數未添加模態中輸入的數據

     load();
     $('form').submit(function(e){
        e.preventDefault();
    Item_Code = $('#Item_code').val();
    Name = $('#Name').val();
    Printer = $('#Printer').val();
    Category = $('#Category').val();
    Price = $('#Price').val();
    Stocks = $('#Stocks').val();
    Image = $('#Image').val();

    $.post('/post',{Item_Code:Item_Code,Name:Name,
    Printer:Printer,Category:Category,Price:Price,
    Stocks:Stocks,Image:Image},function(data){



    $('#Item_Code').val('');
    $('#Name').val('');
    $('#Printer').val('');
    $('#Category').val('');
    $('#Price').val('');
    $('#Stocks').val('');
    $('#Image').val('');
        load();

    });
});
});

我的方法

      public function post(Request $req)
     {
    if($req->ajax()){

    $req->validate([
        'Item_Code'=>'required',
        'Name'=>'required',
        'Printer'=>'required',
        'Category'=>'required',
        'Price'=>'required',
        'Stocks'=>'required',
        'Image'=>'required'

    ]);

    $post = new Menu;
    $post->Item_Code = $req->Item_Code;
    $post->Name = $req->Name;
    $post->Printer = $req->Printer;
    $post->Category = $req->Category;
    $post->Price = $req->Price;
    $post->Stocks = $req->Stocks;
    $post->Image = $req->Image;
    $post->save();

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

我的路線。

 Route::post('/post', 'AdminController@post')->name('create.inventory');

我的情態

    <div class="modal-body">
        <form>
            <label for="required-input" class="require">Item Code:</label>
            <input type = "text" class="form-control" placeholder="Item Code" id = "Item_Code">

            <label for="placeholder-input" class="require">Name:</label>
            <input type= "text" class="form-control" placeholder="Name" id = "Name">

            <label for="single-select" class="require">Printer</label>
                                        <select id="Printer" class="form-control">
                                            <option>Kitchen</option>
                                            <option>Bar</option>
                                        </select>


            <label for="single-select">Category</label>
                                        <select id="Category" class="form-control">
                                            <option>Japanese</option>
                                            <option>Beverage</option>
                                        </select>

            <label for="required-input" class="require">Input Price:</label>
            <input type ="number" class="form-control" placeholder="Price" id="Price">

            <label for="required-input" class="require">Quantity:</label>
            <input type ="number" class="form-control" placeholder="Quantity" id="Stocks">

            <label for="required-input" class="require">Image:</label>
            <input type = "file" class="form-control" id="Image">
        </div>

        <div class="modal-footer">
            <button type="button" class="btn btn-link" data-dismiss="modal">Close</button>
            <button type="submit" class="btn btn-primary">Submit</button>
        </div>
        </form>

422是Laravel 驗證的狀態碼

檢查輸入數據,值之一可能為空

這就是我要做這樣的功能的方式

引導程序模型-我在表單中添加了ID,並且還添加了帶有消息類的div,以用於驗證和成功消息。

<div class="modal-body">
    <div class="messages"></div>
    <form id="productForm">
        {{ csrf_field() }}
        <label for="required-input" class="require">Item Code:</label>
        <input type = "text" class="form-control" placeholder="Item Code" id = "Item_Code">

        <label for="placeholder-input" class="require">Name:</label>
        <input type= "text" class="form-control" placeholder="Name" id = "Name">

        <label for="single-select" class="require">Printer</label>
                                    <select id="Printer" class="form-control">
                                        <option>Kitchen</option>
                                        <option>Bar</option>
                                    </select>


        <label for="single-select">Category</label>
                                    <select id="Category" class="form-control">
                                        <option>Japanese</option>
                                        <option>Beverage</option>
                                    </select>

        <label for="required-input" class="require">Input Price:</label>
        <input type ="number" class="form-control" placeholder="Price" id="Price">

        <label for="required-input" class="require">Quantity:</label>
        <input type ="number" class="form-control" placeholder="Quantity" id="Stocks">

        <label for="required-input" class="require">Image:</label>
        <input type = "file" class="form-control" id="Image">
    </div>

    <div class="modal-footer">
        <button type="button" class="btn btn-link" data-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-primary">Submit</button>
    </div>
    </form>

Ajax代碼

<script>
    var form = $('#productForm');
    var formData = form.serialize();

    var createUrl = '{{ route('create.inventory') }}';

    $('form').on('submit', function (e) {
       e.preventDefault();

       $.ajax({
          url:      createUrl,
          type:     'post',
          data:     formData,
          dataType: 'json',
          success: function (response) {
              var successHtml = '<div class="alert alert-success">'+
                   '<button type="button" class="close" data-dismiss="alert">&times;</button>'+
                   '<strong><i class="glyphicon glyphicon-ok-sign push-5-r"></i></strong> '+ response.message +
                   '</div>';
              var messages = $('.messages');
              $(messages).html(successHtml);
              window.setTimeout(function() {
                  location.reload();
              }, 800);
           },
           error: function(response) {
               var errors = response.responseJSON.errors;

               var errorsHtml = '<div class="alert alert-danger"><ul>';

               $.each( errors, function( key, value ) {
                   errorsHtml += '<li>'+ value[0] + '</li>';
               });
               errorsHtml += '</ul></div';

               $('.messages').html(errorsHtml);
           }
       });
    });
</script>

用於控制器代碼。

確保添加use Validator; 給控制器

現在將在控制器中進行驗證

public function post(Request $request)
{
    if ($request->ajax()) {

        $validator = Validator::make($request->all(), [
            'Item_code' => 'required',
            'Name'      => 'required',
            'Printer'   => 'required',
            'Category'  => 'required',
            'Price'     => 'required',
            'Stocks'    => 'required',
            'Image'     => 'required',
        ]);

        if ($validator->fails()) {
            return response()->json(['success' => false, 'errors' => $validator->errors()], 422);
        } else {
            $post = new Menu([
               'Item_name'  => $request->input('Item_code'),
               'Name'  => $request->input('Name'),
               'Printer'  => $request->input('Printer'),
               'Category'  => $request->input('Category'),
               'Price'  => $request->input('Price'),
               'Stocks'  => $request->input('Stocks'),
               'Images'  => $request->input('Images')
            ]);

            $post->save();

            return response()->json(['success' => true, 'message' => 'success'], 200);
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM