How to incorporate a hyperlink into an Ajax-generated HTML table

I've successfully used thymeleaf in the past, but I'm having trouble implementing it with JavaScript and Ajax get requests.

Essentially, I have a table that is generated dynamically. In my HTML script, an Ajax get request fetches and displays a list of teams in this table. Is there a way to include a link or button after each row that sends the team's ID to my controller when clicked?

Below is my current controller:

$(document).ready(function() {

        // Perform GET request
        $.ajax({
            type: "GET",
            url: "/all",
            success: function(result){
                $.each(result, function(i, team){

                    var customerRow = '<tr>' +
                                        '<td>' + team.id + '</td>' +
                                        '<td>' + team.teamName.toUpperCase() + '</td>' +
                                        '<td>' + team.teamAddress + '</td>' +
                                        '<td>' + team.level + '</td>' +
                                        '<td>' + '<a href="@{/viewteam/{id}(id={team.id})}">' + View Team + '</a></td>' +
                                      '</tr>';

                    $('#customerTable tbody').append(customerRow);

                });

                $("#customerTable tbody tr:odd").addClass("info");
                $("#customerTable tbody tr:even").addClass("success");
            },
            error: function(e) {
                alert("ERROR: ", e);
                console.log("ERROR: ", e);
            }
        });

        // Filter data on view
        $("#inputFilter").on("keyup", function() {
            var inputValue = $(this).val().toLowerCase();
            $("#customerTable tr").filter(function() {
                $(this).toggle($(this).text().toLowerCase().indexOf(inputValue) > -1)
            });
        });
    })

You can see my attempt at implementing it in the 5th <td> tag.

This is the controller where I will pass the ID variable:

@RequestMapping(value="/viewteam/{id}", method=RequestMethod.GET)
public String ViewTeam(Model model, @PathVariable Long id) {



    Team team = teamRepository.findOne(id);

    // The code below ideally returns all players associated with the above team ID in an array list, which will be passed via thymeleaf to display all players


    model.addAttribute("team", team);


    return "singleteam";
}

Answer №1

Seems like the use of inline .Net syntax might be making things too complex here. Since you already have the data from the ajax call, setting the string (as mentioned by @Musa) can be done like this:

'<td><a href="/viewteam/"' + team.id + '">View Team</a></td>' +

Here's a solid example:

var team = {
  id: 1,
  teamName: "Capitals",
  teamAddress: "Capital One Arena",
  level: 9001,
};
var customerRow = ' <tr>' +
      '<td>' + team.id + '</td>' +
      '<td>' + team.teamName.toUpperCase() + '</td>' +
      '<td>' + team.teamAddress + '</td>' +
      '<td>' + team.level + '</td>' +
      '<td>' + '<a href="/viewteam/' + team.id + '">View Team</a></td>' +
    '</tr>';

$('#customerTable tbody').append(customerRow);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="customerTable">
  <tbody>
  </tbody>
</table>

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

The click event is triggering before it is able to be removed by the code preceding the trigger

Here's a scenario I recently experienced that involves some code written using JQuery. It's more of a statement than a question, but I'm curious if others have encountered this as well: <input type="submit" value="Delete" o ...

What might be the reason for the absence of post data when sending it to a CodeIgniter controller through ajax

After going through numerous SO posts addressing the same issue and attempting all recommended solutions, I am still struggling to identify what I am doing incorrectly. Despite being able to log data up to the controller, the post data remains empty consis ...

Treating Backbone Collection as an object instead of an array

Currently, I am working on incorporating nested comments using both Backbone and Rails. In my current setup on the server side, comment models are utilized to store the unique identifier parent_comment_id (assuming they have one). Whenever the application ...

Creating a Dynamic Form in Google App Engine

I need guidance on how to implement a form that communicates with the server in an AJAX manner when the submit button is clicked. The goal is to display information retrieved from the server on the same page. Specifically, I am looking for assistance on ac ...

Saving the created PDF documents on the server

Utilizing the jsPDF plugin, I am currently generating a .pdf file upon clicking a button to initiate a download. Rather than downloading the file, I would like it to be saved onto my server when the button is clicked. Specifically, I want the file to be sa ...

If the first dropdown menu has a sub-element, then the user should be able to select the same value in the second dropdown menu using jQuery

To trigger an alert, two HTML select option dropdowns must both have the value DIP EDU. My current code successfully accomplishes this, but there is a scenario where some options in the first dropdown may contain sub-elements. For example, selecting MBA wi ...

Collaborating and monitoring data between controllers

A unique challenge has arisen as we implement a tree-style navigation element that must communicate with other directives/controllers. The main objectives are: Keep track of the current selection, Detect when the row selection changes. The task at hand ...

What is the process for retrieving randomized data using mongoose?

I recently came across the mongoose-random package which allows for retrieving a JSON array of random records using mongoose. My goal is to retrieve three random records with a specific field. Despite reviewing the documentation, I have yet to find a work ...

Cross-Origin Resource Sharing (CORS) and the use of jQuery

My website is encountering an issue where Firefox is blocking a request that Chrome is able to process without any problems. I'm not sure what I'm doing wrong. Can someone help me out? http://jsfiddle.net/e8qu2g9j/1/ $.ajax({ url: "http://m ...

Is there a way to retrieve the data selected in my modal window when a button is clicked, depending on the v-for value?

As someone who is new to Vue and utilizing Bootstrap modals to showcase product information, I have grid containers that contain a product image, description, and two buttons. One of the buttons, labeled More details >>, is intended to trigger a moda ...

Tips on transferring a numerical ID variable from one page to another by clicking a link

I need help with passing a variable from an auto-generated button to another page when the button is clicked. The buttons all have the same link but different variables. How can I achieve this? Once I generate the button, I assign it a function like so: ...

Monitor Changes with Grunt: Be Prepared for Some Waiting!

My Grunt watch task is experiencing significant delays between detecting a file change and starting to work. Output similar to the following is frequently seen: >> File "src/static/app/brandManager/addChannel.html" changed. Running "html2js:main" ...

How can I eliminate the occurrence of "undefined" during the initial iteration of my for loop that iterates over an array?

How can I prevent getting 'undefined' as the last output when using console.log() with a looping construct? let array = ["Fiji", "Santorini", "Bora Bora", "Vancouver"]; let arrayLength = array.length; for(let index = arrayLength; index >= 0; ...

Adding an active class to a selected list item can easily be accomplished by targeting the

Hey there, I'm attempting to apply a class to the selected list item and also add a class when scrolling to a specific div. For instance, if I scroll to div#six, the number six (6) in the menu should also have the 'active' class. [Check out ...

Formik's handleSubmit function seems to be being overlooked and not executed as

I've encountered an issue while trying to validate a form before submission using formik and yup validation. The form is divided into two parts, where the first part needs to be validated before moving on to the second part. I set a state handleShow(t ...

What is the best way to implement CSS properties dynamically in real-time?

Hey there, I’m working with some HTML code here <div id="div1"></div> I’m dynamically loading content onto this div and adjusting its width in the "success" function based on the contents Here’s the jQuery code snippet I’m using Th ...

Learn how to easily set a radio button using Angular 4 and JavaScript

It seems like a simple task, but I am looking for a solution without using jQuery. I have the Id of a specific radio button control that I need to set. I tried the following code: let radiobutton = document.getElementById("Standard"); radiobutton.checke ...

Retrieving data from a nested object with varying key names through ng-repeat

My JSON object contains various properties with unique names: var definitions = { foo: { bar: {abc: '123'}, baz: 'def' }, qux: { broom: 'mop', earth: { tree: 'leaf', water: 'fi ...

What causes a service called from external of angular to not act as a singleton?

Currently, I am in the process of working on a project that requires me to access a service from outside the Angular service. Unfortunately, it seems that the service retrieved from outside of Angular is not the same instance as the one inside the applicat ...

Dygraphs.js failing to display the second data point

My website features a graph for currency comparison using Dygraphs. Everything was working fine until I encountered this strange issue. https://i.stack.imgur.com/OGcCA.png The graph only displays the first and third values, consistently skipping the seco ...