Input :: all () is empty after passing FormData object
I have a form that I need to process before submitting it. The form has multiple inputs text
and radio
as well file
. I am using jQuery to submit 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 your Laravel controller :
$input = Input::all() // <- EMPTY ARRAY
Don't know why it Input
comes empty. Any help was appreciated.
source to share
Your problem is that you are using GET to send the request with enctype = multipart/form-data
. When you use your own FormData object, this is the default format you get. You can read how to submit form 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 request to GET, your form content present in the request body will be ignored. The enctype attribute is what tells the server how to handle your request. This is why you must use POST.
Please note that when you write
contentType: false,
processData: false
you tell jQuery not to fight with the data you are passing in and leave your own Formdata object untouched. This will automatically set the enctype.
source to share
First, I suggest using the "POST" type to pass your data to your method, and second, try serializing the form data
$.ajax({
type: 'POST',
url: '/get-data', /*Route laravel*/
data: formData.serialize(),
contentType: false,
processData: false
}).done(function(response) {
// handle response
});
source to share
So, I haven't been able to find any resource to confirm this, but it FormData
doesn't seem to work with the type GET
- at least when using the jQuery function $.ajax()
.
Changed GET
to POST
- and the form input enters the Laravel controller without issue.
Not sure if I like this, thought, since I don't really have POST
anything but GET
ting information I need. Either way, it works.
source to share