Limitations of Current Approaches
Although Grails provides the tag to send an HTML formular via AJAX, it is not recommended to use it for at least two reasons:
- The tag is deprecated as of Grails 2.4.0 (see http://grails.org/doc/2.4.0/ref/Tags/formRemote.html)
- The tag works unexpectedly when using it in combination with
g:actionSubmit
Introduction
Suppose we already have a web project with some views that contain some <form>ulars. We now want to replace their default submit behavior with an ajax-based one.
For this reason, we show in this post how to define an ajax-based HTML formular with the help of jQuery.
First, we define the requirements we impose on such a concept. Then, we describe our solution and show an example implementation.
Requirements
- Less modification: We want to modify an existing form tag as less as possible to minimize the modification effort
- Less code: We do not want to encapsulate the ajax functionality within an own tag to keep our project’s code size small and its complexity as simple as possible
A Solution
If we want to ajaxify an existing <form>, we first need to declare it to use ajax—of course.
Moreover, we need to define where the ajax response should be written to.
A common approach is to replace the contents of an html element with this response.
In order to meet requirement 1 (Less modification), we add a CSS class to the target form tag (we name it ajax) indicating that this form should use an ajax-based request on submit.
We then bind an onsubmit
event handler to all form tags that belong to this CSS class.
In this way, we simultaneously meet requirement 2 (Less code) because the event handler with the ajax logics needs to be declared only once at a central place, e.g., in a javascript file.
An Example Implementation
$(function() { $(document.body).on('submit', 'form.ajax', function(event) { event.preventDefaults(); $.ajax({ }).done(function(data) { }); }); });
Thanks. Sure you can.