Reputation: 703
I have an issue in my laravel ajax application,
I cant upload images/files through ajax POST.
here is my code.
Ajax..
/*Add new catagory Event*/
$(".addbtn").click(function(){
$.ajax({
url:'add-catagory',
data:{
logo:new FormData($("#upload_form")[0]),
},
dataType:'json',
async:false,
type:'post',
processData: false,
contentType: false,
success:function(response){
console.log(response);
},
});
});
/*Add new catagory Event*/
Blade template ...
<form enctype="multipart/form-data" id="upload_form" role="form" method="POST" action="" >
<div class="form-group">
<label for="catagry_name">Name</label>
<input type="hidden" name="_token" value="{{ csrf_token()}}">
<input type="text" class="form-control" id="catagry_name" placeholder="Name">
<p class="invalid">Enter Catagory Name.</p>
</div>
<div class="form-group">
<label for="catagry_name">Logo</label>
<input type="file" class="form-control" id="catagry_logo">
<p class="invalid">Enter Catagory Logo.</p>
</div>
</form>
</div>
<div class="modelFootr">
<button type="button" class="addbtn">Add</button>
<button type="button" class="cnclbtn">Reset</button>
</div>
</div>
Controller ..
public function catadd(){
if (Input::hasFile('logo'))
{
return "file present";
}
else{
return "file not present";
}
}
Route ..
Route::post('add-catagory',['as'=>'catagory_add','uses'=>'MastersController@catadd']);
What is the error in my code ???
I cant get the file information in laravel controller..
How can i solve this issue...?
Upvotes: 21
Views: 60715
Reputation: 726
it doesn't work for me because of dataType:'json'
. If anyone gets error just remove dataType:'json'
.
Upvotes: 1
Reputation: 2358
Two things to change:
Change your js file from:
data:{
logo:new FormData($("#upload_form")[0]),
},
To:
data:new FormData($("#upload_form")[0]),
Because you would like to send the whole form.
In your html:
Add a name to your file input field
<input type="file" class="form-control" id="catagry_logo">
To:
<input type="file" name="logo" class="form-control" id="catagry_logo">
Upvotes: 27
Reputation: 10992
Check in your controller what you get when you post:
echo dd(Input::all());
Check files object in php. This in PHP:
$_FILES
Request::file("logo");
Yeah, you're not really posting any data? Is the form really posting?
Upvotes: 1