Laravel 5.5 delete item with ajax call on click

落爺英雄遲暮 提交于 2021-02-07 20:18:36

问题


I am trying to delete a model item via an ajax call when you click on an icon. Without an ajax call and just with a form everything works great.

This exception is thrown when I look in my network tab of my chrome dev tools

"Symfony\Component\HttpKernel\Exception\HttpException"

This is my icon:

<i class="fa fa-trash-o deletebtn" aria-hidden="true" data-pointid="<?php echo $damagePoint->id ?>"></i>

My ajax call:

$(".deletebtn").click(function(ev){
    let pointid = $(this).attr("data-pointid");

    $.ajax({
        url: '/pointdelete/' + pointid,
        type: 'delete',
        success: function (response) {

        }
    });
})

My route:

Route::delete('pointdelete/{id}', 'DamagePointController@delete');

My controller method

public function delete($id)
{
    $todo = DamagePoint::findOrFail($id);
    $todo->delete();

    return back();
}

回答1:


if you are using delete route is like similar to post.Here is the sample code.you can change as per your need

$(".deletebtn").click(function(ev){
    let pointid = $(this).attr("data-pointid");
    $.ajax({
               type: 'DELETE',
               url: '/pointdelete',
               dataType: 'json',
               headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
               data: {id:pointid,"_token": "{{ csrf_token() }}"},

               success: function (data) {
                      alert('success');            
               },
               error: function (data) {
                     alert(data);
               }
    });
});

Route

Route::delete('pointdelete','DamagePointController@delete');

controller

 public function delete(Request $request){

        if(isset($request->id)){
              $todo = DamagePoint::findOrFail($request->id);
              $todo->delete();
              return 'success';
        }
 }



回答2:


Please check below code:

Route::delete('pointdelete',['as' => 'point.delete','uses' => 'DamagePointController@delete']);

<button class="fa fa-trash-o deletebtn" aria-hidden="true" onclick="delete({{ $damagePoint->id }}"></button>

<script type="text/javascript">
function delete(id){

        var _token = "{{ csrf_token() }}";

        $.ajax({
            url     : "{{URL::route('your-delete-route')}}",
            type    : 'delete',
            dataType   : 'json',
            data    :   {
                            'id': id,
                            '_token':_token
                        },
            beforeSend : function() {

            },
            complete   : function() {
            },
            success    : function(resp) 
            {
             console.log(resp);
            }
        });
    }
</script>

public function delete(Request $request,$id)
{
 DamagePoint::destroy($id);

 return response()->json(['success' => true],200);
}



回答3:


Try this kind of ajax call

 $(".deletebtn").click(function(ev){
    let pointid = $(this).attr("data-pointid");

    $.ajax({
        url: '/pointdelete/' + pointid,
        data : {'_method':'delete','_token':'your csrf token'},
        //type: 'delete',
        type:'post',
        success: function (response) {

        }
    });
})

Also, verify that what URL is called in request header information in your chrome developer tools. you just don't need a form try to put your token as {{ csrf_token() }} in ajax.




回答4:


Recently I got the same error and none of above solutions worked for me in laravel 5.7

I had code something like -

$.ajax({
        headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        type:'POST',
        async: false,
        url:validUrl,
        data:{id:1},
        success:function(response){
            if(response && response.error) {
             //show error
            } else {
             // success  
            }
        }

     });

Then I had to set csrf token first using setup method - changed code is something like -

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

    });
 $.ajax({
        type:'POST',
        async: false,
        url:validUrl,
        data:{id:1},
        success:function(response){
            if(response && response.error) {
             //show error
            } else {
             // success  
            }
        }

     });


来源:https://stackoverflow.com/questions/46341260/laravel-5-5-delete-item-with-ajax-call-on-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!