Using JSP in combination with JavaScript for creating dynamic templates

Implementing server-side HTML templating with JSP + JSTL allows for the generation of tables containing user data:

<body>
    ...
    <table>
        <c:forEach items="${users}" var="user">
        <tr>
            <td>${user.name}</td>
            <td>${user.age}</td>
            <td>${user.department}</td>
        </tr>
        </c:forEach>
    </table>
    ...
</body>

This is known as template number 1.

When a user submits new data through a form, AJAX sends the data to the server. Upon success, the new data should be dynamically added to the table without any page reload.

To achieve this, template number 2 can be used. It can either be encapsulated within JavaScript or included in the HTML page with "display: none;" and "class='template'".

<tr class="template" style="display: none;">
    <td>%user.name%</td>
    <td>%user.age%</td>
    ...
</tr>
...
<script>
    $(".template").clone().fillTheTemplateAndAppendToTheTable(user); //just to explain
</script>

The question: Is it possible to avoid duplicating HTML code and have only one universal template in this scenario? If so, how can that be achieved?

Answer №1

One possible solution is as follows:

Template Option 1:

<body>
    ...
    <table id="userTable">
        <c:forEach items="${users}" var="user">
        <%@include file="userRow.jsp" %>
        </c:forEach>
    </table>
    ...
</body>

Contents of userRow.jsp:

<tr>
    <td>${user.name}</td>
    <td>${user.age}</td>
    <td>${user.department}</td>
</tr>

The main action to display the complete table would direct to the first template, while the action managing the ajax call would be linked to userRow.jsp.

In the ajax callback function, simply concatenate the HTML received from the server (the output of executing userRow.jsp) at the end of your table. The JQuery implementation would resemble this example (with createUser.action representing the action that generates a new user utilizing the parameters contained in the user JavaScript object and then redirects to userRow.jsp for rendering the recently added user):

function createUser(user) {
    $.get("createUser.action", user, ajaxCallbackAddingNewUser);
}

function ajaxCallbackAddingNewUser(newUserRow) {
    $("#userTable").append(newUserRow);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discovering the correct element and typing for an HTML attribute through JavaScript

We are currently working on test automation and I am looking for a way to identify the Element and Type associated with it within an html (Data-qa) attribute. For example, when looping through, the Element is identified as input and the type is radio. < ...

Protractor: What is the best way to retrieve the baseUrl from the command line input?

How can I retrieve the baseUrl that was passed through the command line in Protractor? For example: protractor conf.js --baseUrl=http://myawesomesite.com I attempted to use browser.baseUrl to access the baseUrl set in my conf.js file, but it does not see ...

I'm having trouble with res.redirect, why isn't it redirecting me as expected?

In my login controller, I have a form that updates the user's scope when they click a button triggering the login() function. .controller('loginCtrl', ['$scope','$http',function($scope,$http) { $scope.user = { ...

Is it possible to use the identical change function on numerous div elements?

How can functions be bound to multiple div elements effectively? $('#trigger1').change(function(){ // implement the code }); $('#trigger3').change(function(){ // execute the same code }); ...

ajax fails to return a valid request due to an undefined index

I am encountering an issue with my simple AJAX request <script> $(document).ready(function() { setInterval(() => { var val1 = $("#id").val(); var val2 = $("#dt").val(); $.ajax({ ...

Refresh Ajax content every minute for only the first 10 seconds

Currently, I have this code in place and it is functioning correctly. However, I am looking to implement a feature where the page refreshes only during the first 10 seconds of each minute, specifically at 00, 03, 06, and 09 seconds. Can anyone provide as ...

I could use some assistance with iterating through an array that is passed as a parameter to a function

Compute the product of parameter b and each element in the array. This code snippet currently only returns 25. This is because element a[0], which is "5", is being multiplied by argument b, which is also "5". The desired output should be ...

Extract hidden form variables using a function in PHP

Here is the JavaScript function that I have written: function GetCellValues() { var rows = document.getElementsByTagName('tr'); var str = ''; for (var c = 1 ; c < rows.length ; c++) { str += '\n&apo ...

Error in ReactJS: TypeError - Trying to convert undefined or null as an object

Here is the affected code with Typescript errors in local. The component name is correct: {template.elements.map((element: TemplateElementModel, i) => { const stand = roomStands?.find( (stand: ExhibitorModel) => stand.standN ...

What is the best way to restrict datalist options while preserving the "value" functionality?

After finding a creative solution by @Olli on Limit total entries displayed by datalist, I successfully managed to restrict the number of suggestions presented by a datalist. The issue arises from the fact that this solution only covers searching through ...

The Ajax autocomplete feature was unable to find a matching HTTP resource for the requested URI

Seeking assistance with implementing autocomplete functionality on a textbox using data from a web method. The webmethod's browser operation is as follows: http://localhost/psa/DesktopModules/PsaMain/API/ModuleTask/GetIssuers?SearchString=e The resu ...

Adding content to the parent element immediately after it is generated using jQuery

Is there a way to trigger $(e).append() as soon as the element e is created without using setTimeout()? I find that method inefficient. Are there any DOM events that can detect changes in a subtree of a DOM element? Usually, I would just add the code to t ...

Incorporate an icon into a text input field using Material UI and React

I have a form with a text input element: <FormControl className='searchOrder'> <input className='form-control' type='text' placeholder='Search order' aria-label='Search&ap ...

A method for extracting URL parameters based on the matching route path

Is it possible to parse a given URL string in relation to the match.path value? For instance, if the current route is: <Route path="/some/path/:type" /> To obtain the type parameter of the current URL, one can simply use match.params.type ...

Using jQuery Validation and AJAX to update a table row

I have created a table with an edit button for each row that triggers a bootstrap modal when clicked. The modal contains a form populated with information from the table. There is also a submit button on the modal to update the table data. To validate the ...

When I type text into the form field, JavaScript causes a disruption in the form

I'm attempting to implement a dual-stage user onboarding procedure. Initially, users will input the industry they belong to and then provide a description. Upon clicking submit, my intention is to conceal that portion of the form and reveal the "Creat ...

Tips for showing menu only when a user scrolls on your WordPress site

I've been working on creating an effect where the menu stays hidden until the user starts scrolling. However, I can't seem to figure out why my code is not producing the desired effect. Here is the jQuery code snippet I am using: <script src= ...

The property 'scrollHeight' is undefined and cannot be read

I've created a messaging system using javascript and php, but I'm facing an issue. When new messages are received or the chat log grows longer, it creates a scrollbar. The problem is that when a new message arrives, the user has to manually scrol ...

Tips for showcasing the currently active item in a Bootstrap dropdown menu using jQuery

I am trying to highlight the menu item that is selected in a drop-down menu. I attempted the following code, which works if I prevent the default behavior of the link element, but I do not want to do that. So I tried using local storage instead, but it d ...

Refreshing CommonJS modules by reloading or reinitializing them

It is well known that CommonJS modules are designed to load only once. Imagine we have a Single Page application with hash-based navigation; when we go back to a page that has already been loaded, the code does not run again because it has already been loa ...