Ajax-based Form Tag

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:

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

  1. Less modification: We want to modify an existing form tag as less as possible to minimize the modification effort
  2. 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) {
        
        });
    });
});

 

One thought on “Ajax-based Form Tag

Leave a Reply

Your email address will not be published. Required fields are marked *