简体   繁体   中英

how to call delete route with ajax in laravel?

i want to call route resource with ajax, when i put type as delete i got error (exception "Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException") and given message (message "The DELETE method is not supported for this route. Supported methods: GET, HEAD, POST.").function almost work beacuse after make refresh the status also change but i am the above error.

route:

        Route::resource('category', ArtistCategoryController::class);

controller:

 public function destroy($id)
{
    $category = ArtistCategory::findOrFail($id);
    $deleteResponse = $category->update([
       'status'=>'d'
    ]);
    if ($deleteResponse) {
        deleteMessage();
        return redirect()->back();
    } else
        errorMessage();

}

view:

 <a href="" class="categoryDelete" data-id={{ $category->id}} ><i class="far fa-trash-alt" style="color: #b21f2d"></i></a>

ajax:

<script>
    $(".categoryDelete").on('click', function (e) {
        e.preventDefault();
        let id = $(this).data('id')
        // console.log(id)
        $.ajax({
            url: '/artist/category/'+id,
            type: 'DELETE',
            data:{"id": id, "_token": "{{ csrf_token() }}"},
            success: function (data)
            {
                alert(data)
            },
            error: function (e){
                alert(e)
            }
        });
    })
</script>

solved it with some changes in destroy method because i have used return return redirect()->back(); it gives error and this is unacceptable

updated

   public function destroy($id): \Illuminate\Http\JsonResponse
{
    $category = ArtistCategory::findOrFail($id);
    $deleteResponse = $category->update([
       'status'=>'d'
    ]);
    if ($deleteResponse) {
        return response()->json([
            'data' => [
                'id' => $id
            ],
            'status' => 'success',
        ]);
    } else
    {
        return response()->json([
            'data' => [
                'id' => $id
            ],
            'status' => 'error',
            'message' => __("Couldn't Delete. Please Try Again!")
        ], 500);
    }

}

You need to set the csrf token in the header. Have a look at the docs in the bottom of the page: https://laravel.com/docs/8.x/csrf#csrf-x-csrf-token

Create a meta tag with the token like this:

<meta name="csrf-token" content="{{ csrf_token() }}">

And grap it like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM