Reputation: 678
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.
Upvotes: 3
Views: 312
Reputation: 22553
You went the long way around to fix this.
Link tags can send whatever http method you wish, as long as you are handling it in JavaScript and you call preventDefault.
But you have to do it on the event passed into the click handler not on the xhttp pbject. So on your event handler you should have done
event.preventDefault()
and not:
xhttp.preventDefault()
Your form hack isn't idiomatic. It'll freak out the next person who works on that code!
Upvotes: 2
Reputation: 678
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.
Upvotes: -1