'How to call ajax request in Spring boot without page refresh and show the result in thymeleaf page

I am new to spring boot and developing a feature, which will load the result on same page without refreshing it using ajax call in spring boot and show the result on thymleaf.

This is my Thymeleaf code where it is asking to click the button.

<div class="col-md-6 col-lg-4 col-xs-12" id="goimgprofile">
 <form action="" method="post"
                    th:action=@{/user/manageUserPhotoes}
                    name="manageUserPhotoes" id="manageUserPhotoes">
                <div id="Manage-Photo" onclick="showUserPhoto()">
                    <button type="submit" class="ux-pivot width100">
                        <div class="setting-icon">
                            <i class="fa-solid fa-image"></i>
                        </div> <span class="image-name">Photos</span> <span class="image-des">
                        Manage all your photos</span>

                    </button>
                </div>
            </form>

This is the UI on which user will be clicking(above is the code)

enter image description here

This is the line, where I need to show the result on same page without refreshing it.

<div class="img-gallery">
            <div th:each="eachImage: ${allUserPhoto}" class="img-gallery-div">
                <div class="gallery-photo-btn">
                    <ul>

                        <li class="gallery-photo-set-pro" data-toggle="modal" id="set_ProfileImage" data-target="#exampleModal" onclick="confirmImageDeletion(this.id)">Set Profile</li>
                        <li class="gallery-photo-delete" id="delete_ProfileImage" onclick="confirmImageDeletion(this.id)"></li>
                    </ul>
                </div>
                <a href="" th:href="${'data:image/png;base64,'+eachImage}"
                    class="thumbnail"> <img src=""
                    th:src="${'data:image/png;base64,'+eachImage}" alt=""
                    class="img-fluid">
                </a>
            </div>

        </div>

This is my Ajax request to controller.

function showUserPhoto(){
        var url = "/user/manageUserPhotoes"
    $.ajax({
            url : url,
            type: 'POST',
            contentType: 'application/json',
        success: function(result){
            console.log(result.allUserPhoto);
            
        },
        error : function(jqxhr) {
            console.log("error")
        }
    });

}

And this is my controller class where I am fetching the images from database and sending the response.

@PostMapping(value="/manageUserPhotoes",produces=MediaType.APPLICATION_JSON_VALUE)
public String manageUserPhoto(Principal principle, Model model) throws IOException {
    String userEmail = principle.getName();     
    logger.info("user loaded for email "+userEmail +" from ManageUserPhotoController from manageUserPhoto method");
    Users users = this.userRepository.getUserByEmail(userEmail);
    
    List<UserPhoto> userPhotoList = this.userPhotoRepository.getAllUserPhotoByUserID(users.getUsersID());
    logger.info("all photoes received from the userPhoto DB count is: " +userPhotoList.size());
    List<String> allUserPhoto = userPhotoList.stream().map(userPhoto->{
        try {
            return service.getBase64Image(userPhoto.getUserPhoto());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return userEmail;
    }).collect(Collectors.toList());
    System.out.println(allUserPhoto.size());
    model.addAttribute("allUserPhoto", allUserPhoto);
    model.addAttribute("title", "Manage Photo");
    
    
    
    new ResponseEntity<List<String>>(allUserPhoto, HttpStatus.OK);
    return "";
    
}

but don't know what is wrong in here, once Photo button is clicked, it is calling the ajax jquery and it is further calling to the controller but when it is returning the response, page is getting refreshing it and therefore, I am not getting success response.

My current url on which Photo button is showing as http://localhost:8080/user/setting and when calling the controller, it is navigating to http://localhost:8080/user/manageUserPhotoes which I don't want. I want page should remain http://localhost:8080/user/setting and should get the response, so, I can show the result to the page.

What is wrong here, please help me in figuring out here. As I am Very New to Spring boot with ajax call, so, your help is really appreciated.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source