【问题标题】:How to save multiple form data using jquery ajax in laravel?如何在 laravel 中使用 jquery ajax 保存多个表单数据?
【发布时间】:2020-01-18 13:33:20
【问题描述】:

我对此有点困惑。如何使用ajax在laravel中保存多行数据?这个想法是添加产品,当单击提交按钮时,我想将表数据保存在数据库中。我收到一个错误,因为我的控制器中为 foreach 提供的参数无效。

这是我的带有脚本的刀片模板。

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Products Invoice</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
          integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</head>
<body>
<div class="container mt-5">
    <div class="row" id="invoice-data">
        <div class="col-md-12">
            <table class="table table-bordered" id="main_table">
                <thead>
                <tr>
                    <th scope="col">Product Name</th>
                    <th scope="col">Description</th>
                    <th scope="col">Price</th>
                    <th scope="col">Qty</th>
                    {{--<th scope="col">Discount</th>--}}
                    <th scope="col">Amount</th>
                    <th scope="col">
                        <button class="btn btn-success addRow">Add More</button>
                    </th>
                </tr>
                </thead>
                <tbody>
                <tr>
                        <td>
                            <select name="product_name[]" class="form-control productname" id="row_0">
                                <option>Select Product</option>
                                @foreach($products as $product)
                                    <option name="product_name[]" value="{{$product->id}}">{{$product->name}}</option>
                                @endforeach
                            </select>
                        </td>
                        <td><input type="text" name="description[]" class="form-control description" readonly></td>
                        <td><input type="text" id="price" name="price[]" class="form-control price"
                                   onkeyup="rateChange($(this));" readonly></td>
                        <td><input type="text" name="qty[]" class="form-control qty" onkeyup="qtyChange($(this));"
                                   onkeypress='return onlynumbers(event);'></td>
                        {{--<td><input type="text" name="dis[]" class="form-control dis"></td>--}}
                        <td><input type="text" name="amount[]" id="amount" class="form-control amount" readonly></td>
                        <td><a class="btn btn-danger remove">X</a></td>
                </tr>
                </tbody>
            </table>
        </div>
        <div class="col-md-12">
            <div class="form-group float-right">
                <label for="discount"><b>SubTotal</b></label>
                <input type="text" name="subTotal[]" id="subTotal" class="subTotal">
            </div>
        </div>
        <div class="col-md-12">
            <div class="form-group float-right">
                <label for="discount"><b>Discount <span>%</span></b></label>
                <input type="text" name="discount[]" id="discount" class="discount" onkeyup="amount_discount();"
                       onkeypress='return onlynumbers(event);'>
            </div>
        </div>
        <div class="col-md-12">
            <div class="form-group float-right">
                <label for="SubTotal"><b>Total</b></label>
                <input type="text" name="total[]" id="total" class="total" readonly>
            </div>
        </div>
        <div class="col-md-12">
            <div class="form-group float-right">
                <button type="button" id="saveInvoice" name="saveInvoice" class="btn btn-success float-right">Submit</button>
            </div>
        </div>
    </div>
</div>
</body>
<script>
    $("#saveInvoice").click(function () {
        $.ajax({
            url: "{{ route('invoice.store') }}",
            method: "POST",
            data: $("#invoice-data").serialize(),
            dataType: "json",
            success: function (data) {
                console.log(data);
            }
        });
    });
</script>
</html>

这是我存储数据的控制器。

public function store(Request $request)
{
    $invoices = [];
    foreach ($request->input('product_name') as $key => $value) {
        $invoices["product_name.{$key}"] = 'required';
        $invoices["description.{$key}"] = 'required';
        $invoices["price.{$key}"] = 'required';
        $invoices["qty.{$key}"] = 'required';
        $invoices["amount.{$key}"] = 'required';
        $invoices["subTotal.{$key}"] = 'required';
        $invoices["discount.{$key}"] = 'required';
        $invoices["total.{$key}"] = 'required';
    }
    $validator = Validator::make($request->all(), $invoices);

    if ($validator->passes()) {
        foreach ($request->input("product_name") as $key => $value) {
            $invoice = new Invoice;

            $invoice->product_name = $request->get("product_name")[$key];
            $invoice->description = $request->get("description")[$key];
            $invoice->price = $request->get("price")[$key];
            $invoice->qty = $request->get("qty")[$key];
            $invoice->amount = $request->get("amount")[$key];
            $invoice->subTotal = $request->get("subTotal")[$key];
            $invoice->discount = $request->get("discount")[$key];
            $invoice->total = $request->get("total")[$key];

            $invoice->save();
        }
    }
}

它返回 500 内部服务器错误。

【问题讨论】:

    标签: javascript php jquery ajax laravel


    【解决方案1】:

    我认为您需要在 foreach 循环之前打印“$request->input('product_name')”以检查产品名称是否为数组?因为您得到的错误是“在我的控制器中为 foreach 提供的参数无效”。只需写print_r($request-&gt;input('product_name')) 并检查即将到来的值是否为数组?

    【讨论】:

    • 谢谢索希尔。但我不明白为什么它显示为 null ?
    • 在刀片视图文件中,您没有使用
      标签,在按钮单击中,您提交了分配给 div 标签的 ID 为“invoice-data”的序列化数据。因此,使用表单标签并为其提供 id,并在 ajax 脚本中将“invoice-data”id 替换为表单 id。
    • 谢谢索希尔。但是我有一个问题,当我使用表单标签并尝试添加更多行时,我的页面会刷新并且所有数据都会变得清晰。你能帮我解决这个问题吗?
    • 只需在按钮单击脚本中使用 preventDefault 方法即可。Check 了解如何使用它。
    • 它肯定会刷新页面,因为您使用的是按钮标签。使用此按钮添加更多 以防止页面刷新。
    猜你喜欢
    • 1970-01-01
    • 2020-06-15
    • 1970-01-01
    • 2019-04-16
    • 2020-07-31
    • 1970-01-01
    • 1970-01-01
    • 2019-10-27
    • 1970-01-01
    相关资源
    最近更新 更多