Search code examples
javahtmlajaxspringthymeleaf

GET method sent instead of DELETE


I am trying to write the frontend of an application, and I've run into a problem. I've been trying to realize a DELETE method using AJAX, but according to Spring a GET is sent when I run the code.

HTML code:

    <tr th:each="attraction : ${attractions}" th:object="${attraction}">
    <td th:text="*{name}"></td>
    <td th:text="*{latitude}"></td>
    <td th:text="*{city}"></td>
    <td><a th:href="|/edit/*{id}|">EDIT</a></td>
    <script>
        function sendDelete(event) {
            xhttp.preventDefault();
            xhttp.open("DELETE", this.href);
            xhttp.send();
        }
    </script>
    <td><a th:href="|/delete/*{id}|" onclick="sendDelete(event);">DELETE</a></td>
</tr>

Spring code:

  @DeleteMapping("/delete/{id}")
  String delete(@ModelAttribute Attraction attraction) {
   attractionService.delete(attraction);
   return "redirect:/";
  }

How could I solve this problem? Thank you in advance.


Solution

  • With some help, I could figure out the problem. The basic problem is that the
    < a > tag is only able to handle GET methods.

    Instead that part of my code, I sorted it out like this in HTML:

        <td>
            <form th:method="DELETE" th:action="|/delete/*{id}|">
                <input type="submit" value="Send">
            </form>
        </td>
    

    Now it works perfectly.