Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax partial refreshing in post method with spring and thymeleaf

I have problem with partial upating my page. In few sentences I explain business issues. I have user profile where he can change any information about himeself etc: Skills, Personal information, main photo Gallery. All work fine, but I have one annoying thing my whole page refreshes after etc photo adding.

First I show up main photo adding exactly

<div th:fragment="photoDiv">
    <img id="mainPhoto" th:src="@{/profile/main/img}" alt=""/>
    <div>
        <form id="mainPhotoForm" action="#" th:action="@{/profile/main/upload}"
              enctype="multipart/form-data" method="post">
            <label for="files"><img src="../../img/plus.png"/> Upload photo</label>
            <input id="files" style="display:none;" type="file" accept="image/*" th:name="img"
                   onchange="document.getElementById('mainPhotoForm').submit();"/>
        </form>
    </div>
</div>

My controller

@PostMapping("/profile/main/img")
public String uploadingMianPhoto(@RequestParam("img") MultipartFile file,
                                 @ModelAttribute("userDto") userDto user) {
    String path = filesStrorage.storeFiles(file, getCurrentUserID());
    if (!path.isEmpty()) {
        Photo mainPhoto = new Photo();
        mainPhoto.setFileName(file.getOriginalFilename());
        mainPhoto.setPath(path);
        user.setProfilePhoto(mainPhoto);
    }
    return "/profile/edit";
}

// Load main photo
@RequestMapping(value = "/profile/main/upload")
public @ResponseBody
byte[] mainPhotoResponse(@ModelAttribute("userDto") UserDto user) throws IOException {
    Path path = Paths.get(user.getProfilePhoto().getPath());
    return Files.readAllBytes(path);
}

I want only update th:fragment="photoDiv" not a whole page.

I tried ajax fragments update but I don't use a spring webflow, should I adding spring webflow configuration or I can do this by jquery?

So after tries

I adding in uploadingMianPhoto return "/profile/edit :: photoDiv" but it only returns me a just this fragment on my whole page

Please give me some exaples of ajax post function, witch a few explanation words

like image 559
Monika Galińska Avatar asked Feb 26 '17 10:02

Monika Galińska


1 Answers

Yes, you could accomplish this by jQuery. I was able to do so, but it needed some extra javascript effort. I'm gonna show general idea of how I solve such case, using simple example.

At first let's suppose that we have some object to transfer. Nothing special.

SomeDto.java

public class SomeDto {

    private String fieldA;
    private String fieldB;

    // Getters and Setters
}

Secondly, let's have some standard controller with post function to do so. Two things I added "extra" than usual was accepting json request body content and returning fragment.

SomeController.class

@RequestMapping(path = "/some/endpoint", 
                method = ReqestMethod.POST, 
                consumes = "application/json; charset=utf-8")
public String postSomeData(@RequestBody SomeDto someDto) {

    // some action on passed object

    return "some/view :: some-fragment"
}

Then we have a html file with fragment. The trick here is that we post data asynchronously via jQuery ajax, wait for response and replace fragment with this response (because we should received re-rendered fragment).

some/view.html

<!-- Provide id to your fragment element, so that it can be referenced from js -->
<div id="some-fragment" th:fragment="some-fragment">

    <!-- Some rendered data. Omitted -->

    <!-- 
        Don't provide neither action nor method to form,
        cause we don't want to trigger page reload 
    -->
     <form>
        <label for="fieldA">Some field</label>
        <input id="fieldA" type="text" /><br />
        <label for="fieldA">Some field</label>
        <input id="fieldA" type="text" /><br />

        <!-- onclick calls function that performs post -->
        <button type="button" onclick="performPost()">Submit</button>
     </form>
</div>

<!-- 
    Script with logic of ajax call. Should be outside updated fragment.
    Use th:inline so that you could take advantage of thymeleaf's data integrating
-->
<script th:inline="javascript">

    performPost = function() {

        /* Prepare data that have to be send */
        var data = {};
        data.fieldA = $('#fieldA').val();
        data.fieldB = $('#fieldB').val();

        /* Prepare ajax post settings */
        var settings = {

            /* Set proper headers before send */ 
            beforeSend: function(xhr, options) {

                /* Provide csrf token, otherwise backend returns 403. */
                xhr.setRequestHeader("X-CSRF-TOKEN", [[ ${_csrf.token} ]]);

                /* Send json content */
                xhr.setRequestHeader("content-type" ,"application/json; charset=utf-8");
            },
            type: 'POST',
            url: [[ @{/some/endpoint} ]],
            data: JSON.stringify(data)
        }

        /* Send request to backend with above settings and provide success callback */
        $.ajax(settings).done(function(result) {

            /* 
                Replace your fragment with newly rendered fragment. 
                Reference fragment by provided id
            */
            $('#some-fragment').html(result);
        });
    }

</script>

That's all. I hope this will be helpful for you somehow. If I find some time I will try to check this solution with your use case and update answer.

like image 60
Jakub Ch. Avatar answered Oct 05 '22 13:10

Jakub Ch.