Ajax File Upload With Form Data Laravel 5.3
Try using the FormData
in ajax
while you upload a file.
Just try this
$('form').submit(function(event) {
event.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: '{{ url('/agents') }}',
type: 'POST',
data: formData,
success: function(result)
{
location.reload();
},
error: function(data)
{
console.log(data);
}
});
});
OR
You can try with this jQuery
library
https://github.com/malsup/form
EDIT
public function store(Request $request)
{
if (User::where('phone_number', '=', Input::get('phone_number'))->exists()) {
return $this->respondBadRequest('Phone Number Exists');
}
else
{
$user=User::create($request->all());
if($request->hasFile('image')) {
$file = $request->file('image');
//you also need to keep file extension as well
$name = $file->getClientOriginalName().'.'.$file->getClientOriginalExtension();
//using the array instead of object
$image['filePath'] = $name;
$file->move(public_path().'/uploads/', $name);
$user->image= public_path().'/uploads/'. $name;
$user->save();
}
return redirect('agents')->with('Success', 'Agent Added');
}
}
Try something like this:
$('#upload').on('click', function() {
var file_data = $('#pic').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url : 'route_url',
dataType : 'text', // what to expect back from the PHP script, if anything
cache : false,
contentType : false,
processData : false,
data : form_data,
type : 'post',
success : function(output){
alert(output); // display response from the PHP script, if any
}
});
});