Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete file using ajax laravel (404 error)

I'm using ajax to delete a file, but it showed 404 error. I checked route again but i don't know where is wrong! Any solution? Thanks so much!

enter image description here

My Route

Route::post('/deleteFile/ajax/{id}', 'DproductController@deleteFileAjax')->name('delete.file.ajax');

My Controller

public function deleteFileAjax($id)
{
    if (allow('delete') == true) {
        $deleteFile = DproductFile::find($id);
        $deleteFile->delete();
        return response()->json('message', 'Yes');
    } else {
        return response()->json('message', 'No');
    }
}

My View

<a href="#" data-id="{{ $dproductFile->id }}" name="{{ $dproductFile->filename }}" link="{{ route('delete.file.ajax', $dproductFile->id) }}" class="deleteClick red id-btn-dialog2" data-toggle="modal" data-target="#deleteModal">
                                                            <span class="btn-sm btn btn-danger"><i title="Delete" class="ace-icon fa fa-trash-o bigger-130"></i></span></a>

// ajax
<script>
$.ajaxSetup({
     headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
         }
     });

            $('.deleteClick').click(function (e) {
                e.preventDefault();
                var id = $(this).attr('data-id');
                console.log(id);
                $.ajax({
                    url: '/deleteFile/ajax/' + id,
                    type: 'post',
                    dataType: 'json',
                    success: function () {
                        console.log('OK');
                    }
                });
            });
</script>
like image 892
Hoang Dinh Avatar asked Jan 21 '26 03:01

Hoang Dinh


2 Answers

You're using Laravel named routes ->name('delete.file.ajax').

So in AJAX

var path = "{{ route('delete.file.ajax') }}";
$.ajax({
    type: "post",
    url: path,

Personally recommended to use (URL)

Route::post('/deleteFile/ajax/{id}', 'DproductController@deleteFileAjax')->name('delete-file');

In AJAX

var path = "{{ route('delete-file') }}";
like image 121
Abdulla Nilam Avatar answered Jan 22 '26 17:01

Abdulla Nilam


Check the route again with command php artisan route:list.

If everything is fine with the route paths, you may have route caching issue. Do clear route cache with php artisan route:clear command.

like image 29
The_ehT Avatar answered Jan 22 '26 16:01

The_ehT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!