【问题标题】:Laravel upload image through modal using ajax/jqueryLaravel 使用 ajax/jquery 通过模态上传图片
【发布时间】:2020-01-26 16:44:08
【问题描述】:

我正在制作一个包含库存的小型系统。我有一个产品表,其中有一个 image 列,表示特定产品的图片。我的问题是为什么我不能在 Laravel 的项目中使用模态和 ajax 代码上传?有谁知道如何解决这个问题?我已经花了 2 天的时间来弄清楚如何解决这个错误:

消息:“未定义的索引:产品名称”

我已经在我的模型中设置了可填写的字段。非常感谢您的帮助。

模式代码

 <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="exampleModalCenterTitle">Register New Product</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
        <p style="font-weight: bold;">Name </p>
          <input   type="text" class="form-control" id="product_name"/>
          <p style="font-weight: bold;">Description </p>
          <input   type="text" class="form-control" id="description"/>
          <p style="font-weight: bold;">Price </p>
          <input   type="text" class="form-control" id="currentprice"/>
          {{-- <input style="text-transform:uppercase"   type="text" class="form-control" id="supplier_id"/> --}}
          <p style="font-weight: bold;">Supplier </p>
          <select class="form-control"  id="supplier_id"  >
              @foreach ($suppliers as $supplier)
          <option value="{{$supplier->id}}">{{$supplier->name}}</option>
              @endforeach
              </select>
         <p style="font-weight: bold;">Picture </p>
          <input  type="file" class="form-control" id="picture"/>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
          <button type="button" class="btn btn-primary" id="add_product">Add</button>
        </div>
      </div>
    </div>
  </div>

脚本

 $(document).ready(function() {
    //add
    $('#add_product').click(function(e) {
        e.preventDefault();
        var name = $('#product_name').val();
        var description = $('#description').val();
        var price = $('#currentprice').val();
        var supplier_id = $('#supplier_id').val();
        var image = $('#picture').val();

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

        $.ajax({
            url: "{{    url('/product')     }}",
            method: 'post',
            enctype: 'multipart/form-data',
            processData: false, 
            contentType: false,
            data:{
                product_name: name,
                description: description,
                price: price,
                supplier_id: supplier_id,
                image: image,
            },
            success: function (res) {
                console.log(res);
                window.location.href = '{{route("products")}}'
            }
        });
    });
});

ProductsController.php

 public function store(Request $request)
    {
        $data = $request->all();
        $data['product_name'] = ($data['product_name']);
        $data['description'] = ($data['description']);
        $data['supplier_id'] = ($data['supplier_id']);
        $data['price'] = ($data['price']);



        if ($request->hasFile('image')){
            //Add new photo
                $image = $request->file('image');
                $filename = time() . '.' . $image->getClientOriginalExtension();
                $location = public_path('img/' . $filename);
                Image::make($image)->resize(300,300)->save($location);
                $oldFilename = $products->image;
            //Update DB
                $products->image = $filename;
             //Delete the old photo
                // Storage::delete($oldFilename);
            }

        Product::create($data);
        return response()->json($data);
    }

产品路线

//products
Route::resource('product', 'ProductsController');

【问题讨论】:

  • 有人帮助我
  • 你在dd($data)$data = $request-&gt;all();之后看到了什么?
  • 您也可以查看您发布的数据的标题。
  • 我不能dd($data)先生,因为模式不会关闭并且数据没有提交。我真的很想结束这个 T_T @RomanBobrik
  • 标题先生@Phil 是什么意思?

标签: php jquery ajax laravel upload


【解决方案1】:

当服务器需要 JSON 时,似乎您向服务器发送了一个对象。尝试添加dataType:

$.ajax({
    url: "{{ url('/product') }}",
    method: 'post',
    enctype: 'multipart/form-data',
    contentType: false,
    dataType: 'json', // setting of data type
    data:{
        product_name: name,
        description: description,
        price: price,
        supplier_id: supplier_id,
        image: image,
    },
    success: function (res) {
        console.log(res);
        window.location.href = '{{route("products")}}'
    }
});

【讨论】:

  • 遇到同样的错误,先生message: "Undefined index: product_name"。我的代码有什么问题 huhuhu
  • 尝试删除processData: false,
  • 同样的错误先生。现在做什么?先生,我的控制器有什么问题吗?对吗?
【解决方案2】:

我知道这个问题已经很老了,但我在过去几天也遇到过同样的问题,所以我认为答案可能对其他开发人员有用。

您只需要使用 FormData 而不是序列化您的表单。请注意,FormData 需要一个 HTMLFormElement,因此您需要将 [0] 添加到您的 jQuery 对象。而且您不必添加 dataType 指令。

这是我的代码:

$('#submit').on('click', function(e) {
    e.preventDefault();
    $(this).attr('disabled','disabled');
    var form = $(this).closest('form');
    jQuery.ajax({
        type: 'POST',
        processData: false,
        contentType: false,
        data: new FormData(form[0]),
        url: form.attr('action'),
        enctype: 'multipart/form-data',
        headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
        success: function (data) {
            $('#submit').removeAttr('disabled');
            // YOUR SUCCESS MANAGEMENT
        },
        error: function (e) {
            $('#submit').removeAttr('disabled');
            // YOUR ERROR MANAGEMENT
        }
    });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-06
    • 1970-01-01
    • 2017-11-04
    • 2021-07-14
    • 2017-09-28
    • 1970-01-01
    • 2020-07-04
    • 2021-09-05
    相关资源
    最近更新 更多