Home > Net >  Using fetch to change form method to DELETE
Using fetch to change form method to DELETE

Time:01-10

I'm trying to send a form with the DELETE method from a twig template to my PHP controller and I know I have to use the fetch API, but I cannot seem to do it correctly and I don't really understand why. I don't need to send any information since everything is being handled in the PHP part, I just need the form to be of method DELETE. Here is the snippet of code I'm using to send the form:

<form>
       <input onclick="fetch('profile/deleteProfile', {method: 'DELETE'})" type="submit" value="Delete">
</form>

I've tried giving the URL to the fetch method to where the info is and then changing the method to DELETE, the result is the PHP function not activating and I only get a "?" at the end of the url when I click the button

CodePudding user response:

When a submit is triggered, it immediately submits the form unless an onclick handler returns false or the event's default behaviour is prevented.

fetch is an asynchronous/promise-based function, so usually it either needs to be awaited or chained using .then().

However, as you are calling fetch in the onclick handler for your submit, the submit is triggering normally and the fetch does not get to run properly.

If you wish to send a DELETE request then you don't need a form or a submit button. You should also prefer to use event listeners instead of adding Javascript directly into attributes, although there are times where this is necessary.

Solution 1

Change your HTML to this (as in, remove the form tags too)

<button type="button" id="delete">Delete</button>

... and add a script tag at the bottom containing this:

<script>
document.getElementById("delete").addEventListener("click", (e) => {
  e.preventDefault();
  fetch('profile/deleteProfile', {
    method: 'DELETE'
  }).then(res => alert("Done"));
});
</script>

This will add an event listener for the button's click event, send your fetch request (observable in the Network tab of your browser), and then show an alert when the request has finished.

Solution 2

This is only for if you need to leave your HTML as-is, and to just update the onclick attribute

<form>
    <input onclick="fetch('profile/deleteProfile', {method: 'DELETE'}); return false;" type="submit" value="Delete">
</form>

CodePudding user response:

DELETE should be 'DELETE' - it is a string.

  • Related