AJAX files post returning null

Asked

Viewed 80 times

0

I have following HTML:

<meta name="csrf-token" content="{{ csrf_token() }}" />

<form action="{{route('clinic.picture.add.ajax')}}" method="post" 
               enctype="multipart/form-data" id="pic-form">
        @csrf
        <input type="file" name="files" class="form-control form-control-sm" id="add-file">
</form>

When I select the image file I run the following script

$('#add-file').change(function(){
    let form = $('#pic-form')[0];
    let data = new FormData(form);
   // pic.append('file', $('#add-file'))
    $.ajax({
        headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
        enctype: 'multipart/form-data',
        url: "{{asset('clinica/addPicture')}}",
        data: data,
        processData: false,
        contentType: false,
        cache: false,
        type: 'POST',
        success: function(data){
            console.log(data);
        }
    });
});

Rota do Laravel

Route::group(['middleware' => ['auth']], function () {
  Route::prefix('clinica')->group(function () {
    Route::post('/addPicture', 'Clinic\Dashboard\ClinicController@clinicAddPictureAjax')
             ->name('clinic.picture.add.ajax');
 });
});

Method in the controller

    public function clinicAddPictureAjax(Request $request)
    {
        \Log::alert($request);
        try {
            DB::beginTransaction();
            $data = ClinicPictureRepository::createClinicPictures($request,
                                   Auth::user()->id);
            DB::commit();
            return response()->json($data, 200);
        } catch (\Exception $e) {
            DB::rollBack();
            \Log::alert($e->getMessage());
            return response()->json($e->getMessage(), 500);
        }
    }

However when I execute the request to the server it is pointed out that nothing is being sent, this is the log shown in the Standard.

[2019-10-29 12:51:57] local.ALERT: array (
)  

Would anyone know what’s wrong in the relationship?

1 answer

1


Configure:

thus in its

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

this configuration is global in your application and having no more need to use it in all codes, do this routine in a place that will be seen by your other codes . Reference: Laravel csrf token Mismatch for ajax POST Request

The other part of the problem can be solved so by following that <form/>:

$('#pic-form').on('submit', function(event){
  event.preventDefault();
  $.ajax({
   url:"{{ route('clinic.picture.add.ajax') }}",
   method:"POST",
   data:new FormData(this),
   dataType:'JSON',
   contentType: false,
   cache: false,
   processData: false,
   success:function(data)
   {
    console.log(data);
   }
  })
});

Reference: Upload Image in Laravel using Ajax

This way you will solve the problems, in your original code, have wrong and unnecessary settings, which ultimately cause problems in sending the data.

  • Unfortunately this way the request to the server did not even occur...

  • What is the browser window debug error by pressing F12 console tab? @Betinio.Heleno

  • In Laravel&#Xa PHP;php&#xA;array (&#xA; '_token' => '7shXUmsknBVwilpavXqmJe1gyBjlS2hnKhINHtpZ',&#xA; 'files' => &#xA; Illuminate\Http\UploadedFile::__set_state(array(&#xA; 'test' => false,&#xA; 'originalName' => 'download.jpg',&#xA; 'mimeType' => 'image/jpeg',&#xA; 'error' => 0,&#xA; 'hashName' => NULL,&#xA; )),&#xA;)&#xA;

  • No js returns a { } just.... It seems that you are not sending us Multipart/form-data mode',

  • 1

    You were right... It happened that in HTML I forgot to put the name="files[]" so as to understand that it was an array, since my method in the Repository to save is foreach on top of several imanges.. Thank you, your answer was completely correct

Browser other questions tagged

You are not signed in. Login or sign up in order to post.