mardi 18 janvier 2022

Sauvegarder un formulaire avec un appel ajax avec le framework Thymeleaf

Dans cet exemple qui utilise Thymeleaf, nous allons effectuer un post en ajax. Les données envoyés sont de type json. Ce qui a un impact sur le body devant être envoyé et sur l'annotation à employé dans le controller spring.

 Le formulaire est composé de 3 champs.

<form class="row g-3" id="createAdsForm" th:action="@{/ads}">
<input name="id" type="hidden"/>
<div class="col-md-12">
<label for="adsTitle" class="form-label" th:text="#{ads.title}">Title</label>
<input type="text" class="form-control" id="adsTitle" name="title">
</div>

<div class="col-md-12">
<label for="descriptionAds" class="form-label" th:text="#{ads.description}">Example textarea</label>
<textarea class="form-control" id="descriptionAds" name="description" rows="3"></textarea>
</div>

<div class="col-12">
<button type="submit" class="btn btn-primary" th:text="#{ads.publish}">Publié</button>
</div>

</form>

 

FormDataJson provient du dépot: 

https://github.com/brainfoolong/form-data-json

document.addEventListener('DOMContentLoaded', function () {

let createAdsForm = document.getElementById("createAdsForm");

createAdsForm.addEventListener("submit", function(event) {
event.preventDefault();

let jsonSearchAdsForm = FormDataJson.toJson("#createAdsForm", { arrayify: false , flatList: false});
console.log(jsonSearchAdsForm);
fetch(createAdsForm.action, {
method: "post",
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify(jsonSearchAdsForm)
}).then(result => {
if (result.status != 200) {
throw new Error("Bad Server Response");
}
return result.text();

}).then((content) => {
console.log(content);
}).catch((error) => {
console.log(error);
});

});

});

 Au niveau du controller de Spring

@Controller
public class AdsController {

@ResponseBody
@PostMapping("/ads")
public ResponseEntity saveAds(@RequestBody AdsForm adsForm) {

return new ResponseEntity<>(HttpStatus.CREATED);
}

}

 

 Si les données n'auraient pas été envoyé en json, du côté de spring, l'annotation ModelAttribute aurait dû être utilisé.