0

need to save file image using ajax in laravel i use this code

controller

    public function store(Request $request)
{
    $item = new Item;

        // if remove $it_files_path , $it_files_name , $path code work correct 

        $it_files_path = $request->file('file'); 
        $it_files_name = $it_files_path->getClientOriginalName();
        $path = $request->file('file')->storeAs('uploads', $it_files_name, 'public');

        $item->it_photo_name = $it_files_name;
        $item->it_photo_path = $path;

        $item->it_arabic_name = $request->it_arabic_name;
        $item->it_english_name = $request->it_english_name;
        $item->it_classification = $request->it_classification;
        $item->it_weight_gm = $request->it_weight_gm;
        $item->it_dim_length = $request->it_dim_length;
        $item->it_dim_width = $request->it_dim_width;
        $item->it_dim_hight = $request->it_dim_hight;
        
        $item->save();
        $item->id = $item->id;
        return response()->json(['success' => true , 'item' => $item]);
}

if i remove below commented line work correctly

view

<div class="form-group"> 
                <div class="custom-file col-md-12">
                  <label class="custom-file-label">إختر ملفات المنتج (صور-فيديو-وصف..الخ)</label>
                  <input type="file" name="file" class="custom-file-input" id="file">
                  <span class="text-danger" id="fileError"></span>
                </div>
              </div>

here is my ajax code

$.ajax({
  url: 'add-new-item',
  type: "POST",
  data: $('#item,#shp_no_for_it').serialize(),
  success: function(response) {
   if (response.success){
    $('#operation_id').val(response.item.id);
    toastr.success('تم إضافة بيانات المنتج بنجاح');
    } else {
    toastr.error(response.errors.name);
    }
   }
});

here is my Route code

 Route::post('add-new-item', [ItemController::class, 'store']);

i dont know what is wrong in my code

Poles Anwar
  • 11
  • 2
  • 5

1 Answers1

0

You have to use like below code

<form method="post" id="form_submit" enctype="multipart/form-data">
    @csrf
    ....

    <button type="submit" class="btn btn-success"><i class="fas fa-plus fa-xs"></i>Submit</button>

</form>

$(document).ready(function(){
    $('#form_submit').on('submit', function(event){
        event.preventDefault();
        $.ajax({
            url: 'add-new-item',
            method:"POST",
            data:new FormData(this),
            dataType:'JSON',
            contentType: false,
            cache: false,
            processData: false,
            success:function(data){

            }
        })
    })
})

You follow this link also

A.A Noman
  • 5,244
  • 9
  • 24
  • 46