I have a spring boot application with thymeleaf.
I have an input box with a button. When I click on it, I do an ajax call and return a thymeleaf fragment.
I do this ajax call with this code in a fragment
<script type="text/javascript" th:inline="javascript">
document.addEventListener('DOMContentLoaded', function () {
console.log("DOMContentLoaded");
let searchAdsForm = document.getElementById("searchAdsForm")
searchAdsForm.addEventListener("submit", function(event) {
event.preventDefault();
let jsonSearchAdsForm = FormDataJson.toJson(searchAdsForm)
let urlParams = new URLSearchParams(jsonSearchAdsForm).toString();
let url = "/findads?" + urlParams;
fetch(url, {
method: "get"
}).then(result => {
if (result.status != 200) {
throw new Error("Bad Server Response");
}
return result.text();
}).then((content) => {
document.getElementById("main").innerHTML = content;
}).catch((error) => {
console.log(error);
});
}, false);
}, false);
window.addEventListener('load', function () {
console.log("full load page");
}, false);
</script>
It return a table of result. It’s displayed without problem.
Code who return fragment.
@GetMapping("/findads")
public String findAdsBy(Model model, @RequestParam(name="itemToSearch") String search){
System.out.println(search);
Flux<Ads> ads = service.findAds(search);
IReactiveDataDriverContextVariable data = new
ReactiveDataDriverContextVariable((ads));
model.addAttribute("ads", data);
return "fragments/resultsearch::resultSearch";
}
Fragment returned
<div th:fragment="adsResultSearch" class="tabsearch">
<table class="table table-striped">
<tr>
<th scope="col">Donateur</th>
<th scope="col">Titre</th>
</tr>
<tr th:each="ad : ${ads}">
<td><a href="#" th:attr="data-donor=${ad.donor}" th:text="${ad.donor}"/></td>
<td th:text="${ad.title}"></td>
</tr>
</table>
<script type="text/javascript" inline="javascript">
console.log("js");
document.addEventListener('DOMContentLoaded', function () {
console.log("dom ready");
});
document.addEventListener('click', function (event) {
console.log("click");
});
</script>
It’s like the javascript of the fragment return is never running.