Parth Tiwari
Parth Tiwari

Reputation: 486

ajax in Thymeleaf SpringMVC?

How to get fragment in main page using AJAX in Thymeleaf SpringMVC?

I am having Spring MVC and Thymeleaf templating engine. I'm a beginner in Thymeleaf.

I was wondering how can i use ajax to get part of website on how to do simple Ajax request to controller and in result rendering only a part of a template (fragment).

I was trying to return the fragment job.html into home.html

I don't want to use jquery I want to use plain vanilla javascript.

I think i need to use First clone the desired div Second empty the main div Third append the clone into the main div

Here is how my controller look like

   @GetMapping("/generalization")
    public String selectSection(Model model) {
        List<DateasDto> section = generalizationService.getSection();
        model.addAttribute("section", section);
        return "home";
    }

    @GetMapping("/organisations/{id}/general")
    public String getGeneralSuccess(@PathVariable String id , Model model){
        List<AssessmentDto> gen = generalizationService.getGeneral(id);
        model.addAttribute("gen" , gen);
        return "Job";
    }

Here is how my html home.html look like

<body>
<script type="text/javascript" th:src="@{/js/working.js}"></script>

<form onsubmit="getGen(event)" >

    <div class="form-group" >
        <label for="SelectSection">Select Section</label>
        <select  class="form-control" id="SelectSection" onchange="sectionChangeSelected()">
        <option value="">Select section</option>
        <option th:each="section: ${section}"
                th:text="${section.name}"
                th:value="${section.id}"
        ></option>
        </select>
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
</form>

<div id = "table" ></div>

<div th:replace = "Job.html :: myTable " ></div>
</body>

here js look like

    const getGen= (event) => {
        event.preventDefault()
        console.log("get assessment called")
        let id= document.getElementById("SelectSection").value;
        console.log(id)
        let url = `/org/subjects/${id}/assessments`
        fetch(url) 
        .then(function() {
            
        })
        .catch(function() {
            
        });
    }

here is how my Job.html look like

<body>

<div th:fragment = "myTable" >
    <table>
            <thead>
                <tr>
                    <td >Name</td>
                    <td >Date</td>
                </tr>
            </thead>
            <tbody>
                <tr th:each="gen : ${gen}">
                    <td th:text="${gen.Name}"></td>
                    <td th:text="${gen.Date}"></td>
                </tr>
            </tbody>
    </table>
</div>

</body>

Upvotes: 1

Views: 8966

Answers (1)

gtiwari333
gtiwari333

Reputation: 25146

Here's how you can render an HTML on the server side and return asynchronously on Ajax call: In your ajax call you can grab the returned HTML and append to a placeholder div.

    @GetMapping(value = "/theUrl")
    public String aMethod() {
        return "theFileName :: fragmentName "; //THIS
    }

Full example:

The Spring Controller:

@Controller
class Ctrl {
    @GetMapping("/main")
    public String index() {
        return "mainPage";
    }
    @GetMapping(value = "/getMoreMessage")
    public String moreMessage(Model m) {
        m.addAttribute("msg", "Server time is " + ZonedDateTime.now());
        return "frag/ajaxPart :: time-info ";
    }
}

The fragment in resources/templates/frag/ajaxPart.html:

<div th:fragment="time-info" class="tooltip">
    <H2>Received from server:</H2>
    <span th:text="${msg}"></span>
</div>

HTML page for '/main' mapping - mainPage.html

<!DOCTYPE HTML>
<html>
<body>

<script>
    const getData = () => {

        fetch('getMoreMessage').then(function (response) {
            return response.text();
        }).then(function (html) {
            console.log(html)
            document.getElementById("myPlaceHolder").innerHTML += html;
        }).catch(function (err) {
            console.warn('Something went wrong.', err);
        });
    }

</script>

<p><input type="button" onclick="getData( )" value="Get Data"/></p>
<div id="myPlaceHolder"></div>

</body>
</html>

Upvotes: 5

Related Questions