Home > OS >  I get an empty error when submitting multiple forms with file uploads with ajax in laravel
I get an empty error when submitting multiple forms with file uploads with ajax in laravel

Time:03-06

my problem is while posting multiple forms with ajax in laravel, I am sending the form data without any problem, but I cannot send the file. File is empty error. I've been dealing with this for 2 days, there is no method I haven't tried, please help me. Apart from that, I added multipart to the form, but it still didn't work, I'm sharing my codes with you.

Sorry for my bad english.

I want it to upload 2 photos in the normal 4th form until the createProduct3 form, I tried to get them by doing the normal new formData() and I tried otherwise and I couldn't succeed. It sends it to Laravel server side as [Object File]. My Form

<form  id="createProduct4" method="POST" action="">
<input type="file"  id="urun-fotografi" name="urun_fotografi" value="Fotoğraf Seç">
<input type="file"  id="urun-dosyasi" name="urun_dosyasi" value="Dosya Seç">
</form>

My blade ajax:

function createProducts()
{
    var dataString = $("#createProduct1, #createProduct2, #createProduct3, #createProduct4").serialize();
    let photo = document.getElementById("urun-dosyasi").files[0];
    let photo2 = document.getElementById("urun-fotografi").files[0];
    console.log(photo,photo2);

    $.ajax({
        url: "{{ route('user.product.create') }}",
        type: "POST",
        data: dataString "&urun_dosyasi=" photo "&urun_fotografi=" photo2,
        success: function( data ) {

        },
        error: function(xhr)
        {
            console.log(xhr);
        }
    });
}

Server Function

 public function createProduct(Request $request)
{
    $file = $request->file('urun_dosyasi');
    $file2 = $request->file('urun_fotografi');
    $filename = $file->getClientOriginalName();
    $extension = $file->getClientOriginalExtension();
    $filename2 = $file2->getClientOriginalName();
    $extension2 = $file2->getClientOriginalExtension();

    echo $filename,$extension."2. doc: ".$filename2.$extension;
}

CodePudding user response:

Use multipart/form-data when your form includes any <input type="file"> elements :

<form ... enctype="multipart/form-data">

Ajax :

var form = $('#createProduct4')[0];
var data = new FormData(form);

$.ajax({
    url: "{{ route('user.product.create') }}",
    type: "POST",
    enctype: 'multipart/form-data',
    data: data,
    processData: false,
    contentType: false,
    success: function (data) {
        console.log("SUCCESS : ", data);
    },
    error: function (e) {
        console.log("ERROR : ", e);
    }
});
  • Related