Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot Ajax post form submit with model and thymeleaf

Tags:

I have a spring boot controller which returns a view and i wanted to change it by consuming an ajax endpoint, but at the same time get the values from the form with a modelAttribute and then send a list or multiple lists on the page and iterate through those lists with thymeleaf.Is it possible? Here is the controller:

@RequestMapping(value="/search", method=RequestMethod.POST)
    @ResponseBody
    public String search(@ModelAttribute("specification") Specification specification, Model model) {

        List<SearchResultAutovit> list;

        list = scrapper.searchMethod(specification.getPrice,specification.getModel);

        if (list == null || list.isEmpty()) { 
            model.addAttribute("msg","Something"); 
        } else { 
            model.addAttribute("listaAutovit", list); 
        }
        return "?";
    }

Ajax request:

$(".btn.btn-danger").on('click', {function fire_ajax_submit() {
    var str = $(".form-inline.justify-content-center").serialize();

    $.ajax({
        type:"post",
        data:str,
        url:"/search",
        async: false,
        dataType: "json",
        success: function(){
           alert("success");
        }
    });

}

I don't want to manipulate the page from the ajax succes part because i'm already doing that with thymeleaf when the model is sent to the page.

like image 370
Truica Sorin Avatar asked Oct 25 '18 13:10

Truica Sorin


People also ask

How do I submit a form to Thymeleaf?

Write @Controller to handle Form POST request from Thymeleaf In your Spring MVC controller, use the @ModelAttribute annotation to inject the form data. Now you can save this data and show the list of users as I have shown below.

How do I use Ajax in Thymeleaf?

Make an ajax call using the url defined in the form's th:action. Serialize the form data. Your controller will be able to recieve this in an object. Replace the part of your html code with the returned fragment.

How do you pass two objects to a form using Thymeleaf?

The only way I found is to build an other object containing those two objects, and pass it. That works well, but I can't create that kind of object, it's nonsense (even if it works). Of course, the objects aren't as simple as Foo and Bar here, otherwise I would have merge those two.

Can we submit form using Ajax?

We can submit a form by ajax using submit button and by mentioning the values of the following parameters. type: It is used to specify the type of request. url: It is used to specify the URL to send the request to. data: It is used to specify data to be sent to the server.


1 Answers

So what you want is to receive a Thymeleaf fragment using an ajax request. You can achieve this changing your code for the following and adding a fragment where you will add your attributes. We will create an html file called list, where we will have the fragment.

Thymeleaf fragment

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<th:block th:fragment="list">
    <th:block th:if="${list != null}">
        <th:block th:each="iterator: ${list}">
            <!-- Do something -->
        </th:block>
    </th:block>
    <th:block th:if="${msg != null}">
        <p th:text=${msg}></p>
    </th:block>
</th:block>
</body>
</html>

Controller

@RequestMapping(value="/search")
public String search(@ModelAttribute("specification") Specification specification, Model model) {

    List<SearchResultAutovit> list;

    list = scrapper.searchMethod(specification.getPrice,specification.getModel);

    if (list == null || list.isEmpty()) { 
        model.addAttribute("msg", "Error!");
        model.addAttribute("list", list);
    } else { 
        model.addAttribute("list", list);
        model.addAttribute("msg", null);
    }
    return "layouts/list :: list";
}

Then on your ajax you just need to receive the result and append it to an element.

$.ajax({
    type:"post",
    data:str,
    url:"/search",
    dataType: "json",
    success: function(result){
       $(element).append(result);
    }
});

Hope it helps.

like image 171
Alain Cruz Avatar answered Oct 04 '22 04:10

Alain Cruz