I use Spring Boot.
There is a page where all ads are displayed. I need to add ads to favorites. This must be done without navigating to other pages or reloading the current page. So user can click on the button and scroll further, inside it has added to favorites. How can this be done without redirect?
I tried different variants and it doesn't work. Help me please!(
I know that I have to use js, but it doesn't work for me. Also I need to change the method addToFavorites
. Can you change my code and show it clearly?
My HTML:
<div th:each="ad : ${page.getContent()}">
<div>
<div>
<p><a th:href="@{/advert/{id}(id=${ad.getId()})}" th:text="${ad.getHeadline()}">Headline</a></p>
<p th:text="${ad.getDescription()}">Description</p>
<p><i class="fa fa-map-marker" aria-hidden="true" th:text="${dao.getLocation(ad)}"></i> New York</p>
<p><i class="fa fa-clock-o" aria-hidden="true"></i><span th:text="${dao.getDate(ad)}">12.07.2020 19:08</span></p>
</div>
<form th:action="@{/favorites}" method="post">
<input type="hidden" name="ad" th:value="${ad}">
<button type="submit">Add to favorites</button>
</form>
</div>
</div>
My Java:
@GetMapping("/advert")
public String mainPage(@PageableDefault(sort = {"id"}, size = 10, direction = Sort.Direction.DESC) Pageable pageable,
Model model) {
Page<Advert> page = advertDAO.findAll(pageable);
model.addAttribute("page", page);
model.addAttribute("dao", advertDAO);
return "main";
}
@PostMapping("/favorites")
public void addToFavorites(@RequestParam("ad") Advert advert){
// add to favorites
}