Tuesday, June 25, 2019

Spring with Rails' jQuery UJS

I’ve always wanted to try to see if I could use Rails’ jQuery UJS in a Spring Boot project. The UJS in jquery-ujs stands for unobtrusive JavaScript. I really like how UJS wires event handlers to eligible DOM elements marked with HTML5 data-* attributes. I find myself wanting to see more of this approach being used in Spring Boot web apps. I wonder why there’s very little mentioned on the web about this. Or, may be I’ve been looking at the wrong places.

Anyway, here are some things jQuery UJS can do, and the related source code is on GitHub (albeit using a different example).

Non-GET Links (e.g. DELETE)

When I need to render a link that deletes an item, I would use a <button> wrapped in a <form> with a hidden _method field with a value of delete. The <form> is not visible to the user. But the visible button is used to submit the <form>. Some CSS is used to make the button look like a link.

<form action="/articles/42" method="post">
  <input type="hidden" name="_method" value="delete" />
  <button class="btn btn-link">Delete</button>
</form>

Thanks to Spring’s HiddenHttpMethodFilter (also automatically configured in Spring Boot), when this <form> is submitted, it will be received as a request with a method of DELETE. It maps to @DeleteMapping(path="/articles/{id}") in the related @Controller.

While the above works, there is an easier way with jQuery UJS. All that is needed to render a link to delete an item is this:

<a href="/articles/42" data-method="delete">Delete</a>

jQuery UJS will enhance links that have data-method attribute. When the above example link is clicked, the JavaScript will create a <form>. The action attribute of this <form> is set to the value of link’s href. The method is set to post. A hidden _method field is added to the <form> and set to the value of the link’s data-method. Finally, the <form> is submitted (and the link is not followed).

Confirmation Dialogs

Most often than not, when it comes to deleting anything, it would be good to confirm with the user. This could be implemented as a simple dialog via window.confirm(). If we build from the previous example, the <form> would look like this:

<form action="/articles/42" method="post"
    onsubmit="return confirm('Are you sure?')">
  <input type="hidden" name="_method" value="delete" />
  <button>Delete</button>
</form>

While the above works, jQuery UJS shows us a better way. All that is needed to confirm before deleting is this:

<a href="/articles/42?delete" data-method="delete"
    data-confirm="Are you sure?">Delete</a>

jQuery UJS will enhance links (and <form>s too) that have data-confirm attribute. When the above example link is clicked, the JavaScript will call confirm() to show a dialog containing the text that is the value of the attribute. If the user chooses to cancel, the creation/submission of the <form> (due to data-method) does not take place.

Ajax Links

After deleting an item, the page usually reloads to show that the deleted element has indeed been removed.

Let's say the items are displayed in a table. Each row has a unique id.

<table>
  <tr id="article:18">
    <!-- data cells for /articles/18 -->
    <td><a href="/articles/18?delete"
        data-method="delete" data-confirm="Are you sure?">Delete</a></td>
  </tr>
  <tr id="article:42">
    <!-- data cells for /articles/42 -->
    <td><a href="/articles/42?delete"
        data-method="delete" data-confirm="Are you sure?">Delete</a></td>
  </tr>
  <!-- other rows -->
</table>

Assuming that we can simply remove the HTML element that represented the deleted item, then we can probably send the DELETE request asynchronously and get a response that would remove the related HTML element. jQuery UJS makes this as easy as adding data-remote="true" and some minor changes to the server-side controller.

For the HTML, all we need is data-remote="true".

<a href="/articles/42?delete" data-remote="true"
    data-method="delete"
    data-confirm="Are you sure?">Delete</a>

When the link is clicked, jQuery UJS will again send the DELETE request. But this time, it will be sent asynchronously using Ajax. Doing so enables the browser not to reload the entire page. And depending on the server’s response, can update just a portion of the page. Thus, providing a slightly better user experience.

For the server-side controller, we need to send a different response when the request is expecting text/javascript. We add a handler method that will respond with text/javascript by using the produces element of @RequestMapping. The response will remove the related HTML element(s).

// inside a @Controller
@DeleteMapping(path="/articles/{id}")
String delete(... id) {
    // ... delete article with given identifier
    return "redirect:/articles";
}

@DeleteMapping(path="/articles/{id}",
    produces="text/javascript")
String delete(... id) {
    // ... delete article with given identifier
    return "articles/delete";
}

The view is a JSP that contains text/javascript. This will be executed by jQuery UJS.

<%-- articles/delete.js.jsp --%>
<%@ page contentType="text/javascript" %>
$('#article:${id}').remove();

Partials and Server-generated JavaScript Responses

Now what happens if we wanted to have an edit link to get some HTML content and show it up in a modal (without a page refresh)?

Here's what we can do. We send a GET request asynchronously. The response is expected to contain JavaScript that would append the HTML in targeted places in the document, and then trigger the modal to appear.

  <a href="/articles/42?edit" data-remote="true">Edit</a>

When the response is expected to be text/javascript, articles/edit.js.jsp is rendered. Otherwise, the usual articles/edit.jsp is rendered.

// inside a @Controller
@GetMapping(path="/articles/{id}", params={"edit"})
String edit(... id, ...) {
    // ...
    return "articles/edit";
}

@GetMapping(path="/articles/{id}", params={"edit"},
    produces="text/javascript")
String editViaAjax(... id, ...) {
    // ...
    return "articles/edit";
}

The edit.jsp renders the <form> (a partial, not a complete HTML document) which has been refactored to its own JSP to avoid repetition.

<%-- articles/edit.jsp --%>
<!-- -->
  <jsp:include page="_form.jsp" />
<!-- -->

The edit.js.jsp renders the same <form> (a partial, not a complete HTML document) as a string in JS. Then includes it in the modal. It was tricky to render _form.jsp as a string. I had to use <c:import>.

<%-- articles/edit.js.jsp --%>
<%@ page contentType="text/javascript" %>
<c:import var="html" url="…_form.jsp" />
<!-- escape double quotes and remove new lines -->
(function() {
  const $modal = $('#...'); // ID of modal element
  $modal.find('.modal-body').html('${html}');
  if (!$modal.is(':visible')) {
    $modal.modal('show');
  }
})()

For this to work, another InternalResourceViewResolver (IRVR) bean with text/javascript as the contentType is configured. This bean uses the same prefix and a slightly different suffix: .js.jsp. That way, when the request is expecting text/javascript, the CNVR will favor using the IRVR bean with text/javascript and it ends up rendering articles/edit.js.jsp.

Ajax Forms

The data-remote="true" attribute can also be applied to <form>s. With it, jQuery UJS will handle the form submission as an Ajax request. And when the form is being submitted, the buttons can be disabled by adding data-disabled-with. For example,

<form ...>
  <!-- ... -->
  <button data-disable-with="Saving...">Save</button>
</form ...>

When the above form is submitted, jQuery UJS will disable the button and change its content to "Saving...".

Closing Thoughts

I’ve barely touched the surface of Rails’ jQuery UJS. There is so much more that it can offer. I look forward to using it (and similar techniques) in my web apps.