Q8Xbox's avatar

Upload image using Axios + Bootstrap Modal

I'm trying to upload an image in a Laravel 9 project using both Axios and a Bootstrap modal.

When I click on the 'Edit' button jQuery will open a Bootstrap Modal named editCategoryModal with the help of the editCategory function and when I submit the form another function will handle the submission using Axios. In the Controller I used the UpdateCategory function to handle the data save into the database.

I don't understand the things that need to be done when using it with Axios in order to submit the image from Bootstrap Modal and send it to Controller in order to move the image to specific folder & save it in database...?!

categories.blade.php

<div class="edit">
   <button class="btn btn-sm btn-success edit-item-btn" onclick="editCategory({{ $category }})">Edit</button>
</div>

<!-- Edit Modal -->
<div class="modal fade" id="editCategoryModal" tabindex="-1" aria-labelledby="editModalLabel"
   aria-hidden="true">
   <div class="modal-dialog modal-dialog-centered">
      <div class="modal-content">
         <div class="modal-header bg-light p-3">
            <h5 class="modal-title" id="editModalLabel">Edit Category</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"
               id="close-modal"></button>
         </div>
         <form id="EditForm" enctype="multipart/form-data">
            @csrf
            <div class="modal-body">
               <input type="hidden" name="categoryid_efield" id="categoryid_efield">
               <div class="mb-3 form-group">
                  <label for="categoryname_efield" class="form-label">Category Name:</label>
                  <input type="text" name="categoryname_efield" id="categoryname_efield" class="form-control" placeholder="Enter Category Name" />
               </div>
               <div class="mb-3 form-group">
                  <label for="selectImagee" class="form-label">Category Image:</label>
                  <input class="form-control" type="file" name="selectImagee" id="selectImagee">
               </div>
               <div class="mb-3 form-group">
                  <label for="displayImagee" class="form-label"></label>
                  <img class="img-thumbnail" name="displayImagee" id="displayImagee" alt="200x200" width="200" src="https://www.ubertheme.com/wp-content/uploads/sites/3/edd/2014/06/jm-category.png" data-holder-rendered="true">
               </div>
            </div>
            <div class="modal-footer">
               <div class="hstack gap-2 justify-content-end">
                  <button type="button" class="btn btn-light" data-bs-dismiss="modal">Close</button>
                  <button type="submit" class="btn btn-success">Update</button>
               </div>
            </div>
         </form>
      </div>
   </div>
</div>
<!--end edit modal -->
<script type="text/javascript">
   $(document).ready(function (){
        
       $('#selectImagee').change(function(e){
           var reader = new FileReader();
           reader.onload=function(e){
               $('#displayImagee').attr('src', e.target.result);
           }
           reader.readAsDataURL(e.target.files['0']);
       });
   
   });
   
   function editCategory(e) {
           var categoryId  = e.id;
           var categoryName  = e.category_name;
           var displayImage ="";
           if(e.category_image == null){
               displayImage = 'uploads/Noimagefound.jpg';
           }else {
               displayImage = 'uploads/categories/' + e.category_image;
           }
   
           $("#categoryid_efield").val(categoryId);
           $("#categoryname_efield").val(categoryName);
           $('#displayImagee').attr('src', displayImage);
           $('#editCategoryModal').modal('show');
       }
   
       $('body').on('submit', '#EditForm', function(e){
           let id = $('#categoryid_efield').val();
     let data = {
       id: id,
       categoryName: $('#categoryname_efield').val(),
       categoryImage: document.querySelector('#selectImagee').files[0],
     }
     let url = window.location.origin;
     let path = url + '/categories/update' + '/' + id;
   
     console.log(data);
   
     axios.post(path, data, {
         header: {
           'Content-Type': 'multipart/form-data'
         }
       })
       .then(res => {
         /*$('#editCategoryModal').modal('toggle');
         location.reload();*/
         console.log(res)
       })
       .catch(err => console.log(err));
       })
</script>

categoriesController.php

public function UpdateCategory(Request $request, $id) {
$validated = $request->validate([
'categoryName' => 'required|max:255',
]);
$data = "";
if($request->categoryImage){
$file = $request->categoryImage;
$filename = date('YmdHi').$file->getClientOriginalName();
$file->move(public_path('uploads/categories'),$filename);
$data = $filename;
}
$categoryInfo = CategoriesList::find($id)->update([
'category_name' => $request->categoryName,
'category_image' => $data,
]);
return Redirect()->back()->with('success', 'Category Updated Successfully!');
}
0 likes
1 reply
Q8Xbox's avatar
Q8Xbox
OP
Best Answer
Level 1

I have changed submit function to use formData in order to make it work.

$('body').on('submit', '#EditForm', function(e){
const editForm = document.getElementById('EditForm');
const formData = new FormData(editForm);
let url = window.location.origin;
let path = url + '/categories/update' + '/' + formData.get('categoryid_efield');;
axios.post(path, formData, {
header: {
'Content-Type': 'multipart/form-data'
}
})
.then(res => {
/*$('#editCategoryModal').modal('toggle');
location.reload();*/
console.log(res)
})
.catch(err => console.log(err));
})

Please or to participate in this conversation.