Thymeleaf: Refresh value with Ajax Thymeleaf: Refresh value with Ajax ajax ajax

Thymeleaf: Refresh value with Ajax


You can use the feature to only render a fragment of the Thymeleaf view.

First give the snippet of markup you want to update an id:

<span id="eventCount" th:text="${numDeviceEventsWithAlarm}"></span>

Then we can create a Spring request mapping in controller:

@RequestMapping(value="/event-count", method=RequestMethod.GET)public String getEventCount(ModelMap map) {    // TODO: retrieve the new value here so you can add it to model map    map.addAttribute("numDeviceEventsWithAlarm", count);    // change "myview" to the name of your view     return "myview :: #eventCount";}

See Specifying fragments in controller return values in Thymeleaf manual to better understand the return that specifies which fragment to render.

Make a JavaScript function to update the value with ajax (jQuery style):

function updateEventCount() {    $.get("event-count").done(function(fragment) { // get from controller        $("#eventCount").replaceWith(fragment); // update snippet of page    });}

Then just call this function when you need to update the value.