I’m trying to upload image through ajax but i’m not able to get image file on controller as formData always return empty object.
form:
<form id="category_add" method="#">
<div class="card">
<div class="formBlock">
<div class="row">
{{ csrf_field() }}
<div class="col-md-12">
<div class="browseImg">
<i></i>
<span>Uplolad Here</span>
<input type="file" class="browseField" name="image" id="c_image">
</div>
<!-- <div class="formControl static">
<label for="" class="formLabel">Category Name</label>
<input type="text" name="" class="formField" placeholder="Enter your name" id="">
</div> -->
</div>
<div class="col-md-4">
<div class="formControl static">
<label for="" class="formLabel">Category Name</label>
<input type="text" name="name" class="formField" placeholder="Enter your name" id="name">
</div>
</div>
<div class="col-md-4">
<div class="formControl static">
<label for="" class="formLabel">Category Status</label>
<select name="status" class="formField" id="status">
<option value="0">Inactive</option>
<option value="1">Active</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="formControl static">
<label for="" class="formLabel">Position</label>
<input type="text" name="position" class="formField" placeholder="Enter position" id="position">
</div>
</div>
<div class="col-md-12">
<div class="formControl static textarea">
<label for="" class="formLabel">Description</label>
<textarea class="formField" placeholder="Enter your description" rows="5" name="description" id="description"></textarea>
</div>
</div>
</div>
</div>
</div>
<div class="btnBlock d-flex justify-content-end">
<a href="#;" class="btn btn-link btn-md">Cancel</a>
<button type="submit" class="btn btn-md">Add</button>
</div>
</form>
controller:
public function categoryAdd(Request $request)
{
return $data = $request->all();
$rules = [
'name' => 'required',
'status' => 'required',
'position' => 'required',
'description' => 'required',
// 'image'=>''
];
$validator = Validator::make($data, $rules);
if ($validator->fails()) {
$errors = $validator->errors();
$errors = json_decode($errors);
return response()->json(['success' => false, 'error' => 1, 'message' => $errors], 422);
//Toastr::error("All field required");
//return redirect()->route('category.list');
} else {
$token = Session::get('auth_user')['token'];
try {
$url = $this->base_api_url . 'services/category/add/';
if (isset($data['image'])) {
return $apiResponse = Http::withHeaders([
'Authorization' => 'Token ' . $token
])->post($url, [
'data' =>
[
'name' => $data['name'],
'status' => $data['status'],
'position' => $data['position'],
'description' => $data['description'],
'encrypted' => false
],
'c_image' => $data['image'],
"encoded_data" => "yes",
]);
} else {
$apiResponse = Http::withHeaders([
'Authorization' => 'Token ' . $token
])->post($url, [
'data' =>
[
'name' => $data['name'],
'status' => $data['status'],
'position' => $data['position'],
'description' => $data['description'],
'encrypted' => false
],
"encoded_data" => "yes",
]);
}
if ($apiResponse['status'] == false) {
$response['error'] = 1;
$response['success'] = false;
$response['message'] = $apiResponse['message'];
//Toastr::error('category add failed', 'Please Try Again');
return response()->json($response);
} else {
$response['error'] = 0;
$response['success'] = true;
$response['message'] = $apiResponse['message'];
// session(['auth_user' => $apiResponse['data']]);
//Toastr::success('category added successfully');
return response()->json($response);
}
} catch (Exception $ex) {
$response['error'] = 1;
$response['success'] = false;
$response['message'] = $ex->getMessage();
//Toastr::error('Please contact with support', 'Something Went Wrong');
return response()->json($response);
}
}
}
on start i’m returning data but its showing image object empty
ajax request:
$(document).ready(function () {
var home = "{{route('category.list')}}";
$(document).on('submit', '#category_add', function (e) {
e.preventDefault();
let add = "{{route('category.add')}}";
var formData = new FormData(this);
formData.append('c_image', $('#c_image')[0].files[0]);
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
},
type: "POST",
url: add,
contentType: false,
processData: false,
data: formData,
dataType: "json",
success: function (response) {
console.log(response);
if (response.success == true) {
toastr.success("category add successful");
setTimeout(function () {
//window.location.href = home;
}, 2000);
} else {
toastr.error(response.message);
setTimeout(function () {
// window.location.reload();
}, 2000);
}
},
error: function (response) {
if (response.status == 422) {
toastr.error("All field required");
}
else {
toastr.error("Something went wrong");
}
setTimeout(function () {
//window.location.reload();
}, 2000);
}
})
});
});
i’m getting this data after form submit:
{}"_token":"pPHld3dWcEmkVQszMajQZYoqrOLfcm3PmCQzs3GE","name":"check","status":"0","position":"88","description":"test","image":{},"c_image":{}
but as i can see on request payload its showing the data:
2
Answers
You have to use like below
Your form should be like below
Add an id in submit button
Follow this
I tried same code on my local and found these problems in your code..
In Javascript section, remove add variable from ajax request
In Your controller, In my knowledge,it is almost impossible to return requested image object, You will always get empty object.
If you want you can do this too to remove this line from your code because you always get same image with two object key
formData.append(‘c_image’, $(‘#c_image’)[0].files[0]);
In dd function you will get image object
Hope this will help you, Thanks. #happycoding