Laravel 4 restful delete a record with a resource controller

人走茶凉 提交于 2019-12-04 14:03:18

Use $.post() to trigger your click instead of that form creation/submission:

$(document).on("click", "[data-method]", function(e) {
    e.preventDefault();

    $.post($(this).attr('href'), {/* the id goes here */});
});

Apply the cursor style via CSS. I must admit that I'm not sure if laravel expects a HTTP DELETE instead of a post. And I think you missed to submit the id of the department you want to delete.

[edit] As laravel expects a HTTP DELETE you can't use the $.post() shorthand, but $.ajax() instead:

$(document).on("click", "[data-method]", function(e) {
    e.preventDefault();

    $.ajax({
        url: $(this).attr('href'),
        type: "DELETE",
        data: {/* the id goes here */},
        success: function(data, textStatus, jqXHR) {
             console.log("success");
        }
    });
});

The destroy() will be called in DELETE request and not in POST request.

So try ,

<a class="btn btn-xs btn-danger" onclick="deleteDepartment($department->id)" href="javascript:void(0)"><i class="icon-remove"></i></a>

And in javascript,

function deleteDepartment(id) {
  $.ajax({
    url: 'department/'+id,
    type: 'DELETE',
    success: function(result) {
        // Do something with the result
    }
  });
}

Thanks for the answers guys, it works just as it is I just forgot the opening < when creating a form ie I was mistakenly wrote:

"form action='" + $(this).attr('href') + "' method='post' style='display: none;'>\n" + 

Instead of:

"<form action='" + $(this).attr('href') + "' method='post' style='display: none;'>\n" + 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!