Chris
Chris

Reputation: 2181

Laravel 5.5 delete item with ajax call on click

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();
}

Upvotes: 4

Views: 9120

Answers (4)

Vikas Chauhan
Vikas Chauhan

Reputation: 1474

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  
            }
        }

     });

Upvotes: 0

Tarun modi
Tarun modi

Reputation: 1050

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);
}

Upvotes: 4

Vision Coderz
Vision Coderz

Reputation: 8078

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';
        }
 }

Upvotes: 6

Dhaval Purohit
Dhaval Purohit

Reputation: 1290

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.

Upvotes: 1

Related Questions