Refreshing a Thymeleaf table dynamically without having to reload the entire page

I am currently using the Thymeleaf attribute to render data, but I am now looking to add a "Search" button without reloading the page.

Within the attribute departments, I am rendering a List<Department> from the database. While I understand how to achieve this using ajax, it requires me to replace the attribute with a RestController that returns JSON data. Is there a way to fetch data from the attribute without having to reload the page? Perhaps through ajax, JavaScript, or another method?

Answer №1

Achieving this task is possible with the use of fragments and AJAX. In your controller:

@GetMapping("/url")
public ModelAndView getResultBySearchKey()
    {
        List<depatments> areaList= new ArrayList<>();//results from db
        ModelAndView mv= new ModelAndView("search::search_list"); 
        mv.addObject("searchList",areaList);

        return mv;
    }

Additionally, in your search.html file, include the following code snippet and remember to incorporate inline JavaScript.

function loadSearchResult()
    {
    
     $.ajax({
      type: 'get',
      url: /*[[ @{'/url'} ]]*/,
    
      success: function(data){
    
      /*<![CDATA[*/
      
      
      $('.search_list').html(data);
      
      
      /*]]>*/
    },
      
    })
    
    }
<button class="btn btn-primary btn-sm"
th:onclick="'loadSearchResult();'">Search</button>
    <div class="row">


      <div class="col-md-12 search_list">
       <div class="table-responsive" th:fragment="search_list">
         <table
         class="table  table-bordered ">
           <thead>
             <tr>
               <th>SL No.</th>
               <th>Actions</th>
               <th>Name</th>
             </tr>
           </thead>
        <tbody>
    <!-- your desired rows-->
        </tbody>

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

Angular Digest Loop for Dynamic Photo Grid Styling

I have a special filter that alters the objects being filtered. However, when I apply ng-style="item.gridSize", it triggers my custom grid algorithm. This algorithm was adapted for my requirements from a source found at this link. angular.module("custom.m ...

Encoding JSON and parsing data in case no results are retrieved

I am working on an AJAX project using PHP and JQuery, but I have encountered a problem. Specifically, I am facing an issue related to the dataType:"json" parameter in my Javascript code. Everything runs smoothly when the json_encode function returns rec ...

Two interconnected queries with the second query relying on the results of the first

I am currently facing a challenge in my Phonegap (Cordova) application where I need to display a list of items, each requiring an additional query. Let me simplify it with an example scenario. Imagine a student can be enrolled in multiple courses and a co ...

Generating links within a popover using an array in Rails 4

Within my application, Users have the ability to recommend other Users' profiles seamlessly. The functionality related to models and associations is working perfectly, as I am able to identify which users have recommended the current_user's profi ...

Creating visualizations with Django and Highcharts while maintaining a DRY codebase

Currently, I am in the process of developing a server dashboard that heavily relies on graphs and charts. The backend is powered by Django, while we are using Highcharts/Highstock for the graphical representation (though we are also considering D3 dependi ...

Utilizing directives while initiating dynamic components

I've been exploring the capabilities of dynamically creating components using the ComponentFactoryResolver. const factory = this.componentFactoryResolver.resolveComponentFactory(FooComponent); const component = this.templateRoot. ...

What is the best way to assign a jQuery variable to a PHP variable?

After spending some time searching and working on it, I still can't figure out the answer to this straightforward question. Here is the code I have been struggling with. <script> function calculate() { var total = (parseInt($('#stude ...

React input value doesn't get updated on onChange event causing the input

Currently, I'm working on a React application that requires a table with inputs in each row. To achieve this, I am utilizing Material-UI and Formik. However, I've encountered a bug where input fields lose focus whenever I type something into them ...

How can I retrieve the line number of a code during runtime in JavaScript?

Is there a way to add a console.log statement that would indicate the line number it is on in JavaScript? For example: console.log ('Line:', [code to get the line]). The output in the console would be Line: [line number], helping me identify wher ...

Does using AJAX with jQuery and PHP guarantee that the response will always be in JSON format?

While working on PHP validation with AJAX requests for user-submitted information, I encountered an issue. The problem arises when attempting to convert the JSON response from PHP to a Javascript object, as it throws the following error: "Uncaught SyntaxE ...

Ensuring data validity in Angular 2 before enabling a checkbox

In my form, there is a checkbox for admins to edit user accounts. Each user object includes a boolean value isAdmin. I am trying to prevent users from editing their own account while still allowing them to view the values. However, no matter what I try, I ...

Set JSON Value Session

In the table, there is an option to edit certain entries using a button. I have developed a function that retrieves JSON data and populates the table with it. This process happens before any other actions. Once the data is loaded, my goal is to create a c ...

"How can we pause the setInterval when the user hovers over the Ajax Quick Cart and resume it once

Currently, I am working on configuring my Ajax Quick Cart to delay a setInterval function when the user hovers over the cart. The goal is to have the cart close automatically after 3 seconds once an item has been added. However, as I'm not very profic ...

What should I do to resolve the message 'Ignoring invalid configuration option passed to Connection' that I received?

This is the latest message: Warning - Invalid configuration option passed to Connection: createDatabaseTable. Currently a warning, future versions of MySQL2 will throw an error for passing invalid options. The application stops responding after enco ...

Enhance and soften images using CSS with smooth responsiveness across all web browsers

When an image is clicked, it should zoom in and become the background of the page with a blurred effect. I attempted to achieve this using the following code... <style type="text/css"> body{ position: absolute; margin-left: 100px; right: 0; z-inde ...

What is the best way to place a 3D model at random points on the surface of a sphere while ensuring that it always faces the right direction?

I'm faced with the challenge of placing huts randomly on a spherical world. While this task is feasible, the issue arises when the huts do not sit correctly - their bottom should be in contact with the tile below. I've experimented with the &apos ...

Creating a large JSON file (4 GB) using Node.js

I am facing a challenge with handling a large json object (generated using the espree JavaScript parser, containing an array of objects). I have been trying to write it to a .json file, but every attempt fails due to memory allocation issues (even though m ...

What is the best way to transform this JSON data into an array of key-value pairs in JavaScript?

Dealing with nested JSON data can be challenging, especially when trying to extract key-value pairs efficiently. If anyone has suggestions on how to simplify this process and improve readability, please share your insights. The goal is to transform the ne ...

Showing outcomes from various API requests

I have encountered an issue while making two API calls to a backend server and trying to display both responses in JSON format to the user. Strangely, alert 2 is showing as 'undefined' when I check the console, while alert 1 works perfectly fine. ...

Node: permit the event loop to run during lengthy tasks and then return

Currently, I am facing an issue with a function that works like this: function longFunc(par1,par2) { var retVal = [], stopReq = false; function evtLs() { stopReq = true; } something.on("event", evtLs); for(var i=0; ...