简体   繁体   中英

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) .

VerifyCsrfToken.php第46行中的TokenMismatchException

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

UsersController:

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?

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');
    var id = $(this).val();

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

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