Hi Friends,
I am trying to upload an image using ajax in laravel 5.4
Issue :
Formdata is empty on server-side
CODE :
View :
<form role="form" action="{{route('auth.upload')}}" method="post" enctype="multipart/form-data" id="form3">
{{ csrf_field() }}
<h3>Upload Logo</h3>
<div class="form-group">
<label class="custom-file upload-image">
<input type="file" id="image" name="image" class="custom-file-input">
<span class="custom-file-control"></span>
</label>
</div>
<button type="submit" class="btn btn-upload">Save Image</button>
</form>
JS :
$('#form3').on('submit',function(e){
e.preventDefault();
var url = $(this).attr('action'),
post = $(this).attr('method'),
data = new FormData(this);
$.ajax({
url: url,
method: post,
data: data,
success: function(data){
console.log(data);
},
error: function(xhr, status, error){
alert(xhr.responseText);
},
processData: false,
contentType: false
});
});
Route :
Route::post('home/form3', 'HomeController@store')->name('auth.upload');
Controller :
public function store(Request $request){
if ($request->ajax()) {
return $request->all(); // THIS IS RETURNING EMPTY OBJECT
if ($request->hasFile('image')) {
$name = $request->image->getClientOriginalName();
$request->image->storeAs('public/upload',$name);
$company = new Company;
$url = Storage::url($name);
$company->update(['image'=>$url]);
return response(['msg'=>'image uploaded']);
}else{
return response(['msg'=>'No file has selected']);
}
}
}
return response from server side is :
Object {_token: "zFKgoBkdjaIswMG5X0fOyVtaGSYMs84iPDtJA4F5", image: Object}
image : Object
_token : "zFKgoBkdjaIswMG5X0fOyVtaGSYMs84iPDtJA4F5"
__proto__ : Object
I can see only token is returning but not data of uploaded image. If I submit form without using ajax then it is working fine.
Output if submitted without using ajax (this is the output I am expecting even submitted using ajax):
array:2 [▼
"_token" => "eVEjl9UW4rU69oz1lIIiuNABZVpRJFldDST02Nje"
"image" => UploadedFile {#229 ▼
-test: false
-originalName: "empty-normal.png"
-mimeType: "image/png"
-size: 85494
-error: 0
#hashName: null
path: "C:\xampp\tmp"
filename: "php917E.tmp"
basename: "php917E.tmp"
pathname: "C:\xampp\tmp\php917E.tmp"
extension: "tmp"
realPath: "C:\xampp\tmp\php917E.tmp"
aTime: 2017-05-18 11:17:11
mTime: 2017-05-18 11:17:11
cTime: 2017-05-18 11:17:11
inode: 0
size: 85494
perms: 0100666
owner: 0
group: 0
type: "file"
writable: true
readable: true
executable: false
file: true
dir: false
link: false
linkTarget: "C:\xampp\tmp\php917E.tmp"
} ]
Can any one help me in solving this issue ?
**THANKS IN ADVANCE...