【问题标题】:Submitting a form with ajax and laravel使用 ajax 和 laravel 提交表单
【发布时间】:2020-03-25 07:44:26
【问题描述】:

我正在尝试使用 Ajax 将产品添加到数据库而不刷新页面并将数据发送到数据库,但我在控制台上收到错误 Uncaught TypeError: Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.。如何在不刷新页面的情况下提交表单?

刀片

 <form method="POST" role="form" enctype="multipart/form-data">
        {{csrf_field()}}

           <label for="pro_name">Name</label>
           <input type="text" class="form-control" name="pro_name" id="pro_name" placeholder="Enter product name">

           <label  for="category_id">Choose Category</label>
           <select name="category_name" id="category_name">
           <option value=""> --Select Category -- </option>
           @foreach ($categoryname_array as
             $data)
             <option value="{{ $data->name }}"  >{{$data->name}}</option>
             @endforeach
           </select>

           <label for="photos">Choose 5 Images</label>
           <input  "multiple="multiple" name="photos[]" type="file">

           <button type="button" onclick = "submitThisForm({{Auth::user()->id}})" class="btn btn-primary">Submit</button>

    </form> 

阿贾克斯

<script>
function submitThisForm(id){
    let url = "{{ route('product.store', ['id' => ':id']) }}".replace(':id', id);
    $.ajax( {
        url: url,
        type: 'POST',
        data: new FormData( this ),
        processData: false,
        contentType: false,
        success: function(result){
            console.log(result);
        }
    } );
    e.preventDefault();


}
</script>

路线

 Route::post('seller/product', 'ProductController@store')->name('product.store');

【问题讨论】:

  • 您缺少this 的上下文。尝试获取表单,然后创建 FormData 对象var form = $('form')[0]; var formData = new FormData(form);
  • 是那一行,我在哪里把它放在 ajax 代码中?@porloscerrosΨ
  • 我知道了Uncaught ReferenceError: e is not defined @porloscerrosΨ
  • 嗯,这是另一回事。你的函数中有e.preventDefault();,但是e is not defined。删除该行并在您的按钮标签 onclick="event.preventDefault(); submitThisForm({{Auth::user()-&gt;id}});" 上添加阻止
  • 我试图删除 e.preventDefault(); 并将其添加到按钮中,但在控制台中我看到一个像 &lt;script&gt; Sfdump = window.Sfdump || (function (doc) { var refStyle = doc.createElement('style'), rxEsc = /([.*+?^${}()|\[\]\/\\])/g, idRx = /\bsf-dump-\d+-ref[012]\w+\b/, keyHint = 0 &lt;= navigator.platform.toUpperCase(). 这样的长脚本并且它没有提交表单 @porloscerrosΨ

标签: javascript php ajax laravel laravel-5


【解决方案1】:

试试这个。

<form id="myForm" method="POST" role="form" enctype="multipart/form-data">

<script>
function submitThisForm(id){
    let url = "{{ route('product.store', ['id' => ':id']) }}".replace(':id', id);
    var form_data = new FormData(document.getElementById("myForm"));
    $.ajax( {
        url: url,
        type: 'POST',
        data: form_data,
        processData: false,
        contentType: false,
        success: function(result){
            console.log(result);
        }
    } );
    e.preventDefault();


}
</script>

【讨论】:

  • 我得到这样的脚本&lt;script&gt; Sfdump = window.Sfdump || (function (doc) { var refStyle = doc.createElement('style'), rxEsc = /([.*+?^${}()|\[\]\/\\])/g, idRx = /\bsf-dump-\d+-ref[012]\w+\b/, keyHint = 0 &lt;= navigator.platform.toUpperCase(). 并且按钮没有提交@BCM
  • 试试这不是答案。请解释该代码的作用
【解决方案2】:

我认为你把事情复杂化了。

首先,您的路线不需要任何参数。

Route::post('seller/product', 'ProductController@store')->name('product.store');

所以你不需要传递它。

{{ route('product.store', ['id' => ':id']) }} // remove , ['id' => ':id']

那么,既然你使用的是jquery,你就可以在表单的submit方法上处理ajax调用了。

$('form').on('submit', function (e) {
    e.preventDefault(); // prevent the form submit
    var url = '{{ route('product.store' }}';
    // create the FormData object from the form context (this),
    // that will be present, since it is a form event
    var formData = new FormData(this); 
    // build the ajax call
    $.ajax({
        url: url,
        type: 'POST',
        data: formData,
        success: function (response) {
            // handle success response
            console.log(response.data);
        },
        error: function (response) {
            // handle error response
            console.log(response.data);
        },
        contentType: false,
        processData: false
    });
})

在您的表单中,您不需要按钮上的 onclick 事件..

<form method="POST" role="form" enctype="multipart/form-data">
    {{csrf_field()}}

    <label for="pro_name">Name</label>
    <input type="text" class="form-control" name="pro_name" id="pro_name" placeholder="Enter product name">

    <label  for="category_id">Choose Category</label>
    <select name="category_name" id="category_name">
    <option value=""> --Select Category -- </option>
    @foreach ($categoryname_array as $data)
        <option value="{{ $data->name }}"  >{{$data->name}}</option>
    @endforeach
    </select>

    <label for="photos">Choose 5 Images</label>
    <input  "multiple="multiple" name="photos[]" type="file">

    <button type="button" class="btn btn-primary">Submit</button>

</form> 

【讨论】:

  • 这看起来很干净,我没有收到任何错误,但按钮仍然没有将数据提交到数据库@porloscerros Ψ
  • 在数据库中保存数据发生在后端。这是 Laravel 的工作,不能通过 ajax 调用将数据保存在数据库中。打开一个新问题:“如何处理接收到的数据以将其保存在数据库中?”在ProductControllerstore函数中添加你有什么,你收到什么数据,以及你的模型和数据库结构。
猜你喜欢
  • 2015-02-05
  • 2015-10-25
  • 2016-12-16
  • 1970-01-01
  • 2016-10-31
  • 2016-12-10
  • 2016-06-11
  • 2019-05-04
  • 1970-01-01
相关资源
最近更新 更多