如何使用ajax在laravel中保存多行表单?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何使用ajax在laravel中保存多行表单?相关的知识,希望对你有一定的参考价值。

嘿伙计们我对此有点困惑。如何使用ajax在Laravel 5.5中输入多行表单?想法是添加项目,当添加项目编号增量时,我想将此表保存在我的数据库中:enter image description here

Here is my code for the blade with its script:

上Aitmskbledkphp

@extends('layouts.app')
@section('content')

<div class="container-fluid">
<!-- Your main wrapper -->

    <div class="row">
        <div class="col-md-12">
            <div class="panel panel-default">
                <div class="panel-heading"><h3 class="panel-title">Add Items</h3></div>
                <div class="panel-body">

                    <form name="add_item" id="add_item" class="form-inline">
                     csrf_field() 


                      <div class="form-group">
                        <label for="pr_form_number">PR Form Number: </label>
                        <input type="text" class="form-control" name="pr_number" value="$pr_details" readonly required><br><br>
                      </div>

                      <div class="table-responsive">
                        <table class='table table-bordered table-hover' id="tab_logic">
                            <thead>
                                <tr class='info'>
                                    <th style='width:10%;'>ITEM NO.</th>
                                    <th style='width:10%;'>QTY</th>
                                    <th style='width:10%;'>UNIT</th>
                                    <th style='width:30%;'>DESCRIPTION</th>
                                    <th style='width:10%;'>COST PER UNIT</th>
                                    <th style='width:10%;'>COST PER ITEM</th>
                                    <th style='width:10%;'>ACTION</th>
                                </tr>
                            </thead>
                            <thead>
                                <tr id="addr0">
                                    <td class="custom-tbl"><input class='form-control input-sm'style='width:100%;' type="text" value="1" id="pr_item0" name="pr_item[]" readonly required></td>
                                    <td class="custom-tbl"><input class='form-control input-sm' style='width:100%;' type="text" id="pr_qty0" oninput='multiply(0);' name="pr_qty[]"></td>
                                    <td class="custom-tbl"><input class='form-control input-sm' style='width:100%;' type="text" id="pr_unit0" name="pr_unit[]"></td>
                                    <td class="custom-tbl"><input class='form-control input-sm' style='width:100%;' type="text" id="pr_desc0" name="pr_desc[]"></td>
                                    <td><input class='form-control input-sm' style='width:100%;' type="text" id="pr_cpu0" oninput='multiply(0);' name="pr_cpu[]"></td>
                                    <td class="custom-tbl"><input class='estimated_cost form-control input-sm' id="pr_cpi0" style='width:100%;' type="text" name="pr_cpi[]" readonly></td>
                                    <td class="custom-tbl"><button type="button" id="add" class="btn btn-info btn-sm"><span class="glyphicon glyphicon-plus"></span></button></td>
                                </tr>
                            </thead>
                            <tbody id="dynamic_field">

                            <tbody>
                            <tfoot>
                                <tr class='info'>
                                    <td style='width:65%;text-align:right;padding:4px;' colspan='5'>GRAND TOTAL:</td>
                                    <td style='padding:0px;'>

                                            <input style='width:100%;' type='text' class='form-control input-sm' id='grand_total' name='grand_total' value='0' readonly required>

                                    </td>

                            </tfoot>

                        </table>
                      </div>


                      <button type="button" id="submit" name="submit" class="btn btn-default">Submit</button>
                    </form>

                </div>

            </div>
        </div>

    </div>


</div>



@endsection

@section('script')
<script type="text/javascript">



$(document).ready(function()      
      var postURL = "<?php echo url('addmore'); ?>";
      var i=1;  


      $('#add').click(function()
           i++;  
           $('#dynamic_field').append('<tr id="row'+i+'" class="dynamic-added"><td class="custom-tbl"><input id="pr_item'+i+'" class="form-control input-sm"style="width:100%;" type="text" value="'+i+'" name="pr_item[]" readonly required></td><td class="custom-tbl"><input id="pr_qty'+i+'"class="form-control input-sm" style="width:100%;" type="text" oninput="multiply('+i+');" name="pr_qty[]"></td><td class="custom-tbl"><input id="pr_unit'+i+'"class="form-control input-sm" style="width:100%;" type="text" name="pr_unit[]"></td><td class="custom-tbl"><input id="pr_desc'+i+'" class="form-control input-sm" style="width:100%;" type="text" name="pr_desc[]"></td><td class="custom-tbl"><input id="pr_cpu'+i+'" class="form-control input-sm" style="width:100%;" type="text" oninput="multiply('+i+');" name="pr_cpu[]"></td><td class="custom-tbl"><input id="pr_cpi'+i+'" class="estimated_cost form-control input-sm" style="width:100%;" type="text" name="pr_cpi[]" readonly></td><td class="custom-tbl"><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn-sm btn_remove"><span class="glyphicon glyphicon-remove"></span></button></td></tr>');  
      );  


      $(document).on('click', '.btn_remove', function()  
           var button_id = $(this).attr("id");   
           $('#row'+button_id+'').remove();  
      );

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


      $('#submit').click(function()            
           $.ajax(  
                url:"route('pr.items.add')",  
                method:"POST",  
                data:$('#add_item').serialize(),
                type:'json',

           );  
      );  

    );




</script>

<script type="text/javascript">
    function multiply(id)
        
            var total1=parseFloat($('#pr_qty'+id).val())*parseFloat($('#pr_cpu'+id).val());
            $("input[id=pr_cpi" + id + "]").val(total1);
            grandTotal();
        
function grandTotal()
        
            var items = document.getElementsByClassName("estimated_cost");
            var itemCount = items.length;
            var total = 0;
            for(var i = 0; i < itemCount; i++)
            
                total = total +  parseFloat(items[i].value);
            
            document.getElementById('grand_total').value = total;
        
</script>

@endsection

And here is a part of my controller for storing its data

PurchaseRequestItemController.php

 public function store(Request $request)
    
        //


        $rules = [];


        foreach($request->input('pr_item') as $key => $value) 
            $rules["pr_item.$key"] = 'required';
            $rules["pr_qty.$key"] = 'required';
            $rules["pr_unit.$key"] = 'required';
            $rules["pr_desc.$key"] = 'required';
            $rules["pr_cpu.$key"] = 'required';
            $rules["pr_cpi.$key"] = 'required';
        


        $validator = Validator::make($request->all(), $rules);


        if ($validator->passes()) 


            foreach($request->input('pr_item') as $key => $value) 

                $Record=new PurchaseRequestItemModel;

                $Record->pr_form_number = $request->get('pr_number');
                $Record->item_no = $request->get('pr_item');
                $Record->pr_qty = $request->get('pr_qty');
                $Record->pr_unit = $request->get('pr_unit');
                $Record->pr_description =$request->get('pr_desc') ; 
                $Record->pr_cost_per_unit =$request->get('pr_cpu') ;
                $Record->pr_estimated_cost =$request->get('pr_cpi') ;

                $Record->save();
            


            return response()->json(['success'=>'done']);
        else

        return response()->json(['error'=>$validator->errors()->all()]);




    

编辑:我的表格也是一个数组。我如何确保保存后我可以查看表格原样?

当我保存enter image description here时,它也会返回此错误

答案

例如$ request-> get('pr_number');这是一个数组,因此在不定义索引的情况下无法获取特定值。您必须定义数组的索引。试试这个。希望它会奏效。

foreach($request->input('pr_item') as $key => $value) 

            $Record=new PurchaseRequestItemModel;

            $Record->pr_form_number = $request->get('pr_number')[$key];
            $Record->item_no = $request->get('pr_item')[$key];
            $Record->pr_qty = $request->get('pr_qty')[$key];
            $Record->pr_unit = $request->get('pr_unit')[$key];
            $Record->pr_description =$request->get('pr_desc')[$key]; 
            $Record->pr_cost_per_unit =$request->get('pr_cpu')[$key];
            $Record->pr_estimated_cost =$request->get('pr_cpi')[$key];

            $Record->save();
        
另一答案

用这个

$pr_item=$request->get('pr_item');
$pr_qty=$request->get('pr_qty');
$pr_unit=$request->get('pr_unit');
$pr_desc=$request->get('pr_desc');
$pr_cpu=$request->get('pr_cpu');
$pr_cpi=$request->get('pr_cpi');
for($i = 0; $i < count($request->get('pr_item')); $i++)
            $Record=new PurchaseRequestItemModel;
            $Record->pr_form_number =    $request->get('pr_number');
            $Record->item_no =           $pr_item[$i];
            $Record->pr_qty =            $pr_qty[$i];
            $Record->pr_unit =           $pr_unit[$i];
            $Record->pr_description =    $pr_desc[$i]; 
            $Record->pr_cost_per_unit =  $pr_cpu[$i];
            $Record->pr_estimated_cost = $pr_cpi[$i];
            $Record->save();
        
另一答案
 Use $request->all() and fetch values as below it will work.

 foreach( $request->all() as $value ) 
    $record = new PurchaseRequestItemModel;
    $record->pr_form_number = $value['pr_number'];
    $record->item_no = $value['pr_item'];
    $record->pr_qty = $value['pr_qty'];
    $record->pr_unit = $value['pr_unit'];
    $record->pr_description =$value['pr_desc')];
    $record->pr_cost_per_unit =$value['pr_cpu')];
    $record->pr_estimated_cost =$value['pr_cpi')];
    $record->save();

另一答案

希望对你有帮助

foreach($request->input('pr_item') as $key => $value) 

     $item = new PurchaseRequestItemModel;
     $item ->pr_form_number = $request->get('pr_number')[$key];
     $item ->item_no = $request->get('pr_item')[$key];
     // mention other fields here
     $item ->save();

以上是关于如何使用ajax在laravel中保存多行表单?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 laravel 中验证多行表单

如何使用 ajax 在 laravel 5 中发布表单?

如何在 Laravel 中使用 Ajax 调用将数据发布到数据库?

如何修复 Laravel 5.8 Ajax 表单提交中的内部服务器错误

如何在 MySQL 数据库的多行中保存表单数据(表单内的表)

Laravel 中的 Ajax Jquery 未将值保存到数据库