2

In my application I need to upload a cover image for a dish.

Here's my AJAX call:

$('#addDishForm').submit(function(e) {
    e.preventDefault();
    var el = $(this);
    var formAction = el.attr('action');
    var formValues = el.serialize();
    console.log(formValues);

    $.ajax({
        type: 'POST',
        url: '/admin/menu',
        data: new FormData(el[0]),
        success: function (data) {
            console.log(data);
        },
        error: function(data) {
            console.error(data);
        }
    });
}); 

I have an error as a result return from controller in console.

Uncaught TypeError: Illegal invocation

What is the workaround?

Here is the controller's method:

public function store(Request $request)
{
    if($request->hasFile('cover_image'))
    {
        return response()->json([ 'success' => true, 'message' => 'File exists' ]);
    }
    else 
    {
        return response()->json([ 'success' => false, 'message' => 'File doesn\'t exist' ]);
    } 
}

A route:

Route::middleware('auth')->prefix('/admin')->namespace('Admin')->group(function () {
    // other routes ...
    Route::post('/menu', 'MenuController@store');
    // other routes ...
});

Here's the form:

{!! Form::open([ 'method' => 'POST', 'enctype' => 'multipart/form-data', 'id' => 'addDishForm' ]) !!}
    // other form controls ...
    {{ Form::file('cover_image', [ 'class' => 'dropify', 'data-max-file-size' => '2M' ]) }}
    // other form controls ...
{!! Form::close() !!}

1 Answers1

4

The illegal invocation comes from jQuery trying to serialize a FormData object, when specifying a FormData object as the data parameter to jQuery.ajax you must tell jQuery not to process the data by setting the field processData to false.
Also jQuery will set the content type which you do not want with FormData and to prevent this set contentType to false.

$.ajax({
    type: 'POST',
    url: '/admin/menu',
    data: new FormData(this),
    processData: false,
    contentType: false,
    success: function (data) {
        console.log(data);
    },
    error: function(data) {
        console.error(data);
    }
});
Musa
  • 96,336
  • 17
  • 118
  • 137