Input::all() empty after FormData object passed

1.8k views Asked by At

I have a form that I need to process before it's submitted. The form has several text and radio inputs, as well as a file one. I'm using jQuery to pass the form data:

$button.on('click', function(e) {
    e.preventDefault();

    var formData = new FormData($('.js-my-form')[0]);

    $.ajax({
        type: 'GET',
        url: '/get-data',
        data: formData,
        contentType: false,
        processData: false
    }).done(function(response) {
        // handle response
    });

});

Then, in Laravel controller:

$input = Input::all() // <- EMPTY ARRAY

No idea why Input comes empty. Any help appreciated.

3

There are 3 answers

0
devconcept On BEST ANSWER

Your problem is that you are using a GET to send a request with enctype = multipart/form-data. When you use a native FormData object this is the format that you get by default. You can read how to send the form's data

using the POST method and setting the enctype attribute to application/x-www-form-urlencoded (default);

using the POST method and setting the enctype attribute to text/plain;

using the POST method and setting the enctype attribute to multipart/form-data;

using the GET method (in this case the enctype attribute will be ignored).

So if you set your requesto to a GET the content of your form present in the body of the request will be ignored. The enctype attribute is what tells the server how to process your request. This is why you should use POST.

Note that when you write

contentType: false,
processData: false

you are telling jQuery that do not mess with the data you are passing and leave your native Formdata object untouched. This will cause the enctype to be set automatically.

2
envynoiz On

First i suggest use a type 'POST' to pass your data at your method and second, try serialize the form data

 $.ajax({
        type: 'POST',
        url: '/get-data', /*Route laravel*/
        data: formData.serialize(),
        contentType: false,
        processData: false
    }).done(function(response) {
        // handle response
    });
0
lesssugar On

So, I could not find any resource to confirm this, but it seems FormData won't work with GET type - at least when using jQuery's $.ajax() function.

Changed GET to POST - and the form input is getting to the Laravel controller with no problems.

Not sure I like it, thought, as I'm actually not POSTing anything, but GETting information I need. Anyways, it works.