我尝试使用 Ajax 将产品添加到数据库而不刷新页面并将数据发送到数据库,但出现错误 Uncaught TypeError: 无法构造“FormData”:参数 1 不是类型控制台上的“HTMLFormElement”。
。如何在不刷新页面的情况下提交表单?
Blade
<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>
Ajax
<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');
最佳答案
我认为你把事情过于复杂化了。
首先,您的路线不需要任何参数。
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>
关于javascript - 使用 ajax 和 laravel 提交表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59109384/