最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I send a DELETE request when a button is clicked? - Stack Overflow

programmeradmin3浏览0评论

I am using the resource controller in Laravel 8 and I want to hit its delete method from a delete button. How can I create a button with method='delete'? I have to create this in JavaScript as the button is in a table and I have created with JS.

My Edit button is like this:

<a href='"+base_url+"/donner/"+user['donner_id']+"/edit'>
    <button class='btn btn-sm btn-outline-warning'>
        <i class='fa-solid fa-pen-to-square'></i>
        &nbsp;&nbsp;Edit
    </button>
</a>

For the delete button, I have to send a request with the delete method.

I am using the resource controller in Laravel 8 and I want to hit its delete method from a delete button. How can I create a button with method='delete'? I have to create this in JavaScript as the button is in a table and I have created with JS.

My Edit button is like this:

<a href='"+base_url+"/donner/"+user['donner_id']+"/edit'>
    <button class='btn btn-sm btn-outline-warning'>
        <i class='fa-solid fa-pen-to-square'></i>
        &nbsp;&nbsp;Edit
    </button>
</a>

For the delete button, I have to send a request with the delete method.

Share Improve this question edited Jun 17, 2024 at 10:54 double-beep 5,52019 gold badges40 silver badges48 bronze badges asked Apr 2, 2022 at 10:09 Usama JalalUsama Jalal 1551 gold badge1 silver badge10 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

It's not possible to send a DELETE request directly from pure HTML. You can either use JavaScript to send the DELETE request, or some frameworks support passing the method as a parameter in a POST request body.

<form action="/delete" method="POST">
    <input type="hidden" name="_method" value="DELETE" />
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
    <input type="submit" value="Delete">
</form>

This technique uses a form who's only visible input is a button. When the button is clicked it submits the form sending a POST request to the server. The server then detects the "_method" field and treats it as a DELETE request.

You can learn more about method spoofing in the Laravel docs.

Take a look on the example code below. It shows you what are the steps. Bind a js trigger to the button. Then use fetch or axios or whatEverToMakeJSApiCalls.

Note Im sure that the next problem will e. CSRF, etc

<button 
  class=""
  onclick="deleteSomething( {{$id}} )">
</button>
function deleteSomething(id) {
  fetch('/api/deleteModelName/' + id,  {
    method: 'DELETE'
  })
}
<a onclick=&nbsp;sendDelete('"+base_url+"/donner/"+user['donner_id']+"/delete')&nbsp;><button class='btn btn-sm btn-outline-warning'><i class='fa-solid fa-pen-to-square'></i>&nbsp;&nbsp;Delete</button></a>
function sendDelete(p) {
  var xhr = new XMLHttpRequest();
  xhr.open("DELETE",p);
  xhr.send();
}
发布评论

评论列表(0)

  1. 暂无评论