Reputation: 1620
I am using laravel 5. I have did the following code to post data using json to my controller. But I cannot make file uploading by this manner.
e.preventDefault();
$.ajax({
type: 'POST',
cache: false,
dataType: 'JSON',
url: 'tasks',
data: $('#my_form').serialize(),
success: function(data) {
console.log(data);
},
});
I have the following html code to upload files.
<input type="text" name="name" value="" />
<input type="text" name="name" value="" />
<input type="file" class="form-control" name="documents[]" multiple>
How can I send file using json in laravel? I have did many search but I cant get proper solution
Upvotes: 0
Views: 2232
Reputation: 2465
Use this as your code:
e.preventDefault();
var mydata = new FormData($('#my_form')[0]);
$.ajax({
type: 'POST',
cache: false,
dataType: 'JSON',
url: 'tasks',
data: mydata,
processData: false,
contentType: flase
success: function(data) {
console.log(data);
},
});
Note that this doesn't work on some older browsers such as IE 9 or older so you might need to disabled this feature to prevent your errorlogs from overloading, I give my users a custom message that the feature is disabled in older browsers by using
if(typeof FormData !== 'undefined'){
var formdata = new FormData($("#documentform")[0]);
}
else{
$("#errormsg").val("upload feature is disabled in this browser version");
return false;
}
Upvotes: 1
Reputation: 1686
The standard jquery ajax don't support directly the sending of files. To do it, you basicly need too use the FormData
object instead of a standard js one for your post parameter collection.
You will also need to disable 2 parametters in the ajax option :
processData: false,
contentType: false,
to prevent jquery from interfering with the FormData Object.
More info here : https://stackoverflow.com/a/8244082/4734683
Upvotes: 0