4

I have being searching everywhere for the past 6 hours and I can't find the answer to my question. I have a data table that display a list of users. I have an column that has an icon that looks like a trash can. The idea is when a user press the icon that gets erase using ajax. This is my first time using ajax and laravel.

This is my view

<td>
    <button class="btn btn-danger btn-xs" id="destroy" data-id="5"><i class="fa   fa-trash-o "></i>
    </button>
</td>

This is my script

$(document).ready(function(){

    $("#destroy").click(function()
    {

        var id = $(this).data("id");

        $.ajax(
        {
            url: "http://localhost:8888/users/destroy",
            type: 'DELETE',
            dataType: "JSON",
            data: {
                "id": id
            },
            success: function ()
            {
                console.log("it Work");
            }
        });

        console.log("It failed");
    })

});

This is my route

Route::delete('users/destroy', 'UsersController@destroy');

this is my controller

public function destroy()
{
    $id = input::get('id');
    $id = User::findorfail($id);
    $id->delete();
}

This the errror I get

TokenMismatchException in VerifyCsrfToken.php line 46:\

3
  • possible duplicate of Laravel 4 CSRF form submit through Ajax call Commented Mar 5, 2015 at 18:47
  • The base URL of the page that launches the ajax should match exactly the location the ajax is hitting. Can you verify that your main page is on the same domain? localhost:8888 Commented Mar 5, 2015 at 19:42
  • FYI, you should only use IDs on elements if they are single elements. You should apply the destroy class to them rather than ID. Commented Mar 5, 2015 at 20:09

2 Answers 2

2

Add &_token={{ csrf_token() }}in data array after id parameter.

Sign up to request clarification or add additional context in comments.

Comments

0

View

<td>
    <input type="hidden" value="<?php echo csrf_token(); ?>" name="_token">
    <button class="btn btn-danger btn-xs" id="destroy" data-id="5"><i class="fa   fa-trash-o "></i>
    </button> </td>

Script

$(document).ready(function(){

    $("#destroy").click(function()
    {

        var id = $(this).data("id");
        var token = $('input[name="_token"]').val();

        $.ajax(
        {
            url: "http://localhost:8888/users/destroy",
            type: 'DELETE',
            dataType: "JSON",
            data: {
              "_token": token,
                "id": id,

            },
            success: function ()
            {
                console.log("it Work");
            }
        });

        console.log("It failed");
    })

});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.