0

I work with a Spring boot and JSP project and the UI is provided below,

enter image description here

I would like to delete the row entries using the delete button. The page list.jsploads with the controller method,

@GetMapping(value = "/")
public String index() {
    return "redirect:/users";
}

@GetMapping(value = "/users")
public String showAllUsers(Model model) {

    model.addAttribute("users", userService.findAll());
    return "list";
}

The JSP part for the buttons are in the list.jsp page,

<td>
                    <spring:url value="/users/${user.id}" var="userUrl"/>
                    <button class="btn btn-info" onclick="location.href='${userUrl}'">Query</button>

                    <spring:url value="/users/${user.id}/delete" var="deleteUrl"/>

          <button class="btn btn-danger" onclick="this.disabled=true;removeUser()">Delete</button>

                    <spring:url value="/users/${user.id}/update" var="userUpdate"/>
                    <button class="btn btn-info" onclick="location.href='${userUpdate}'">Update</button>
                </td>

The controller mapping for the deletion,

@DeleteMapping(value = "/users/{id}/delete")
    public String deleteUser(@PathVariable("id") Long idx, final RedirectAttributes redirectAttributes) {

        logger.debug("Delete user with Id {}", idx);

        redirectAttributes.addFlashAttribute("css", "Success");
        redirectAttributes.addFlashAttribute("msg", "The user is deleted");

        // delete the user
        userService.delete(idx);
        return "redirect:/users/";
    }

I have the JavaScript function in the custom file,

function removeUser(){

}

and, after clicking the delete button, I can get some console output, which means the delete button is working. How should I implement the removeUser function that will delete the rows after clicking the button?

I would like to know if I can do this with any built-in methods from the jQuery as well. Thanks.

The Query and the Update buttons have respective controller methods and work properly.

If I leave it just like

<spring:url value="/users/${user.id}/delete" var="deleteUrl"/>

it doesnt delete the row or do anythong

Update

I can pass the delete URL to the custom JavaScript function,

<spring:url value="/users/${user.id}/delete" var="deleteUrl"/>
                    <button class="btn btn-danger" onclick="this.disabled=true;removeUser('${deleteUrl}')">Delete</button>

The removeUser fucntion provided,

function removeUser(deleteURL) {

    console.log("Remove : " + deleteURL);

    $.ajax({

        type: "DELETE",
        url: deleteURL,

        success: function () {

        },

        failure: function (errMsg) {
            console.log(errMsg.toString())
        }
    });
}

I have tried to write the success function, not working though

Arefe
  • 11,321
  • 18
  • 114
  • 168
  • 1
    Make an Ajax request to /users/{id}/delete and in the success handler remove the relevant row from your table. See https://stackoverflow.com/a/42055209/1356423 or https://stackoverflow.com/questions/1141793/jquery-ajax-remove-rows-from-table-and-in-db – Alan Hay Oct 05 '17 at 13:58
  • Would you please have a look at the updated question? I have tried to write the success function, not working though. An answer with code will be helpful – Arefe Oct 05 '17 at 14:20
  • 1
    Look at the network traffic in your browsers DEV tools. Your controller is probably returning a redirect (302 status) i.e not a status 200 (OK) response required to trigger the client side success handler. Update your controller method using something like: https://stackoverflow.com/a/25572820/1356423 – Alan Hay Oct 05 '17 at 14:27
  • 1
    the problem is your redirect, you are using a RestController, so yours methods have implicit ResponseBody, which means you can not redirect from your controller. You should get the payload from your controller, and decide what to do in your JS file – cralfaro Oct 05 '17 at 14:31
  • I dont use `RestController` as you mentioned. My code `@Controller public class UserController { ...}` – Arefe Oct 05 '17 at 14:33
  • @AlanHay this works now and I wrote a brief answer – Arefe Oct 05 '17 at 15:11

1 Answers1

1

The comments under the questions very helpful and I manage to do it with a minimal amount of code. The button in the JSP page calls removeUser function,

<tr id="myTableRow">
                <td><c:out value="${user.id}"/></td>
                <td><c:out value="${user.name}"/></td>
                <td><c:out value="${user.email}"/></td>
                <td><c:forEach var="framework" items="${user.framework}" varStatus="loop">
                    ${framework}
                    <c:if test="${not loop.last}">,</c:if>
                </c:forEach>
                </td>

                <td>
                    <spring:url value="/users/${user.id}" var="userUrl"/>
                    <button class="btn btn-info" onclick="location.href='${userUrl}'">Query</button>

                    <spring:url value="/users/${user.id}/delete" var="deleteUrl"/>
                    <button class="btn btn-danger" onclick="removeUser('${deleteUrl}')">Delete</button>

                    <spring:url value="/users/${user.id}/update" var="userUpdate"/>
                    <button class="btn btn-info" onclick="location.href='${userUpdate}'">Update</button>
                </td>
            </tr>

The removeUser function,

// delete the user from the database
function removeUser(deleteURL) {

    $.ajax({

        type: "DELETE",
        url: deleteURL,

        success: function () {
            // window.location.reload();
             $('#myTableRow').remove();
        },

        failure: function (errMsg) {
            console.log(errMsg.toString())
        }
    });
}

The controller to delete the row from the MySQL,

@DeleteMapping(value = "/users/{id}/delete")
    @ResponseStatus(value = HttpStatus.OK)
    public String deleteUser(@PathVariable("id") Long idx, final RedirectAttributes redirectAttributes) {

        logger.debug("Delete user with Id {}", idx);

        redirectAttributes.addFlashAttribute("css", "Success");
        redirectAttributes.addFlashAttribute("msg", "The user is deleted");

        // delete the user
        userService.delete(idx);
        return "redirect:/users/";
    }

I use @ResponseStatus(value = HttpStatus.OK) as suggested because I was getting 302 returned from the controller and have verified in the network section of the Chrome dev tool.

Arefe
  • 11,321
  • 18
  • 114
  • 168
  • Okay, but the whole point of using Ajax in the first place was to avoid the page reload so I am not sure what you have achieved: server responds 200 OK then you know server deletion successful so you simply need to remove the corresponding row from the table on the client and not refresh the whole page. – Alan Hay Oct 05 '17 at 15:15
  • How can I achieve it without reload? Some code example will be good – Arefe Oct 05 '17 at 15:16
  • 1
    https://stackoverflow.com/questions/170997/what-is-the-best-way-to-remove-a-table-row-with-jquery – Alan Hay Oct 05 '17 at 15:17