sklrboy sklrboy - 11 days ago 5
Javascript Question

Laravel5 ajax delete wouldn't work

I'm working on a project, where I should delete users from the

users
table with ajax. I've been seeking for multiple solutions, but it just simply wouldn't work anyhow. Here's the error I'm getting:


Failed to load resource: the server responded with a status of 500 (Internal Server Error).


TokenMismatchException in VerifyCsrfToken.php line 46

JS:

$('.btn-delete').click(function(){
var id = $(this).val();
$.ajax({

type: 'DELETE',
url: '/laravel-exercise/public/index/'+id,
success: function (data) {
console.log('Success:', data);
},
error: function (data) {
console.log('Error:', data);
}
});
});


View:

<button class="btn btn-danger btn-delete" value="{{$user->id}}" data-token="{{ csrf_token() }}">Delete</button>


Route:

Route::delete('index/{$id}', 'UsersController@destroy');


destroy():

public function destroy($id)
{
$user = User::findOrFail($id);
$user->delete();

return view('pages.index')->with([
'flash_message' => 'The user has been deleted.',
'flash_message_important' => 'true',
]);
}


What is going wrong here?

Answer

Probably it's due to the CSRF protection.

Try to add the 'X-CSRF-TOKEN' before you bind the button click.

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

$('.btn-delete').click(function(){
    var id = $(this).val();
    $.ajax({
        type: 'DELETE',
        url: '/laravel-exercise/public/index/'+id,
        success: function (data) {
            console.log('Success:', data);
        },
        error: function (data) {
            console.log('Error:', data);
        }
    });
});

To add the CSRF token to your request.

Have a look here for infos about.

The route is found, otherwise i'll catch a 404 exception.

edit

Looking at how you made the button, you could also use a post request, but passing a _method data.

HTML:

<button class="btn btn-danger btn-delete" value="{{$user->id}}"
     data-token="{{ csrf_token() }}">Delete</button>

Javascript:

$('.btn-delete').click(function(){
    var token = $(this).data('token');

    $.ajax({
        url: '/laravel-exercise/public/index/'+id,
        type: 'post',
        data: {_method: 'delete', _token :token},
        success: function (data) {
            console.log('Success:', data);
        },
        error: function (data) {
            console.log('Error:', data);
        }
    });
});
Comments