Search code examples
javascriptajaxspring-mvcthymeleaf

Pass value to controller via AJAX without any user input using Thymeleaf


I want to create a button where I can delete a user. I want to send the user ID from Thymeleaf to my Spring MVC Controller via AJAX without any user input.

However all the examples I've seen use forms and form data. In my case I want to send data that I already have from Thymeleaf without using a form. How can I go about doing this?

  <tr th:each="user : ${userList}">
        <th scope="row"><span th:text="${user.id}"></span></th>
        <td><span th:text="${user.username}"></span></td>
        <td><span th:text="${user.email}"></span></td>
        <td width="60">
            <div class="dropdown">
                <button class="btn btn-light btn-block dropdown-toggle text-right" type="button" data-toggle="dropdown"><span th:text="${user.roles[0].role}"></span>
                    <span class="caret"></span></button>
                <ul class="dropdown-menu">
                    <div th:each="role : ${user.roles}">
                        <span th:href="@{'/users/manageRole' + ${user.id}}" th:text="${role.role}"></span>
                    </div>
                </ul>
            </div>
        </td>
        <td>
            I want to send ${user.id} as a DELETE method to /admin/users from Thymeleaf here

            My attempt without AJAX using URL parameter : 
            <form method="DELETE" th:action="@{'/admin/users/' + ${user.id}}"
                <button type="submit" class="btn btn-light btn-block" id="submit">Delete User</button>
            </form>
            Problem with this implementation is the button redirects to /admin/users/${user.id}, 
            I don't want any redirects. I also would prefer not to show the user ID as a parameter in the URL.

        </td>

Solution

  • Store the user id in a hidden input (or any other html element):

    <input id="userIdInput" th:value="${user.id}" hidden>
    

    Then retrieve it in js and make the ajax call you need (an example assuming you are using JQuery; put this in a function and call it on button click or whatever suits your needs):

    $.ajax({
        url : '...',
        type : 'POST',
        data : $("#userIdInput").val(),
        cache : false,
        contentType : false,
        processData : false,
        success : function(returndata) {
            ...
        },
        error : function() {
            ...
        }
    });