Shawn Javadi Shawn Javadi - 19 days ago 5
Ajax Question

How to use AJAX with Eloquent ORM to delete records?

I'm using Slim framework + Eloquent ORM. I want to delete records with an ajax request. Only problem is that when I press the button to trigger the request, I get a 405 (method not allowed) error back. My route is a delete route and I've set the type to DELETE as well

what I have for my AJAX request so far:

$(".deleteYell").click(function(){
var id = $(this).data("id");
token = $(this).data("token");
$.ajax(
{
url: "/yell/"+id,
type: 'DELETE',
dataType: "JSON",
data: {
"id": id,
"_method": 'DELETE',
"_token": token,
},
success: function ()
{
console.log("it Work");
}
});

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


my route is as follows:

$this->delete('/yell/{id}', 'UserController:deleteYell')->setName('deleteYell');


and here's the button that is used to delete the post:

<button class="deleteYell" data-id="{{ post.id }}" data-token="{{ csrf }}" type="button" name="button">Delete</button>


What should I change for this to work?

Answer

You have to use POST method.give it a try

$(".deleteYell").click(function(){
var id = $(this).data("id");
    token = $(this).data("token");
$.ajax(
{
    url: "/yell/"+id,
    type: 'POST',
    data: {
        "id": id,
        "_method": 'DELETE',
        "_token": token,
    },
    success: function ()
    {
        console.log("it Work");
    }
});

console.log("It failed");

});