I am attempting to pass an ID to the Controller using a dynamic button, however, I am encountering difficulties in doing so

I need to pass the object's id to the controller when a button is clicked. Right now, it only works for the first item in the list and not for others. How can I fix this issue?

$(document).ready(function () {
  $("#showTweet").click(function () {
    var tweetId = $(this).parent().attr("id");
    $.ajax({
      type: "GET",
      dataType: "json",
      url: "http://localhost:8020/showTweet?tweetId=" + tweetId,
      success: function (result) {
        var description = result.description;
        $("#tweetText").text(description);
      },
    });
  });
});

    
<table id="myTable" class="table table-striped">
  <thead>
    <tr>
      <th>User</th>
      <th>Creation Date</th>
      <th>Options</th>
    </tr>
  </thead>
  <tbody>
    <tr th:each="unapprovedTweets: ${unapprovedTweets}">
      <td th:text="${unapprovedTweets.creative}"></td>
      <td th:text="${unapprovedTweets.create_date}"></td>
      <td>
        <div th:id="${unapprovedTweets.id}" style="width: 0px; height: 0px; display: contents;">
          <a id="showTweet" class="btn btn-warning">View Tweet</a>
        </div> <a th:href="@{'/sendTweet/' + ${unapprovedTweets.id}}" class="btn btn-primary" style="width: 90px; margin-left: 5px;">Approve</a>
        <a th:href="@{'/refuseTweet/' + ${unapprovedTweets.id}}" class="btn btn-danger" style="width: 90px; margin-left: 5px;">Reject</a>
      </td>
    </tr>
  </tbody>
  </table>

Answer №1

Utilize a data-... attribute with th:attr to manage the id's:

Substitute:

<div th:id="${unapprovedTweets.id}"
     style="width: 0px; height: 0px; display: contents;">

with:

<div th:attr="data-tweetId=${unapprovedTweets.id}" 
     style="width: 0px; height: 0px; display: contents;">

Within your JavaScript, employ:

$(document).ready(function(){       
            $("#showTweet").click(function(){
         var tweetId = $(this).parent().attr('data-tweetId');
        $.ajax({
        
        type: "GET",
        dataType: "json",
        url: "http://localhost:8020/showTweet?tweetId="+tweetId,
        success: function(result){
            var description = result.description;
            $('#tweetText').text(description);
            
             }
        });
    });

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

When attempting to post data using jQuery, an object is encountered that does not have a parameterless constructor

Here is the code snippet I am using with jQuery to post data and register a band: var formData = new FormData(); var file = document.getElementById("CoverPicture").files[0]; formData.append("file", file); var Name = $('#Name').val(); var Genre = ...

Ways of converting a negative lookbehind into an ES5-friendly expression

In my code, I have a RegExp that works perfectly, but it only functions with ES2018 due to its use of negative lookbehinds. The problem is that a library is using this RegExp function, so modifying how it's used is not an option. I attempted to add n ...

The issue with additional parameters not functioning in jQuery autocomplete

JavaScript Issue $('input.completeme').each(function() { $(this).autocomplete({ source: function(request, response) { $.ajax({ url: '<?=base_url()?>patients/autocomplete', data: { & ...

Having difficulties executing AJAX requests on Codepen.io

My CodePen project that I created 6 months ago is no longer functioning properly. The project includes an Ajax call to retrieve data using jQuery.ajax(). When attempting to load the content from CodePen via https, even though the ajax request is through h ...

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. ...

Reset dropdown selection when a search query is made

Currently experimenting with Angular to develop a proof of concept. Utilizing a functional plunker where selecting an option from a dropdown populates a list of items from an $http.get( ). Additionally, there is a search input that should trigger its own $ ...

Can Ajax be utilized to invoke an internal function within a web application?

Brand new to PHP, this is a whole new world for me. Currently, I am attempting to dynamically update a drop down list from 1-10 based on the selection of a previous drop down list. The initial drop down list allows you to choose tables numbered 1-35, whil ...

Tips and tricks for displaying JSON data in Angular 2.4.10

In my Angular project, I am facing an issue while trying to display specific JSON data instead of the entire JSON object. Scenario 1 : import { Component, OnInit } from '@angular/core'; import { HttpService } from 'app/http.service'; ...

Grabbing an AJAX Request

Currently, I am working on a Firefox extension that is designed to analyze the HTML content of web pages after they have been loaded in the browser. While I have successfully captured events like form submissions and link clicks, I am facing an issue wit ...

Discovering mistakes in PHP MySQL

Is there an error in this code? Here's the code I'm working with. Thank you in advance for your help! else if(isset($_POST['UPDATECSSGOLD'])) { $stmt = $mysqli->prepare("UPDATE css set STYLE_STATUS = 'allnull'"); $stmt-& ...

Use jQuery to populate a span element with information that is solely obtainable within a foreach loop during the rendering of buttons

I am currently navigating through learning MVC, and I have hit a roadblock. Working with Web Forms was more familiar to me, so I find myself struggling quite a bit with this new framework. After dedicating most of my day to it, I realize I need some assist ...

Encounter a Socket.io connection error due to net::ERR_CONNECTION_REFUSED when trying to access from multiple devices

I'm having trouble with other people's computers accessing my test chatting application. When they try to connect, they encounter this error: localhost:3000/socket.io/?EIO=4&transport=polling&t=Oi2Ko0C:1 Failed to ...

Steps to create a custom function that can manage numerous onclick actions to toggle the visibility of a specific field

I'm relatively new to coding and JavaScript. I'm working on a basic webpage that involves showing and hiding parts of sentences for language learning purposes. Is there a way to create a single function that can show and hide the sentence when a ...

Designing a unique diagonal layout with HTML and CSS

Hey there, I have a question about creating diagonal backgrounds in web design. I've seen websites like Udacity and one my friend is working on that feature diagonal shapes or designs in the background. I'm curious about how to achieve this effec ...

The class .is-invalid transforms into .is-valid when rendered

Currently, I am incorporating bootstrap into my react project. In this case, I have a variable called mobile that needs to undergo validation whenever there is a change in the input field. Below is the code snippet for the component: const EnterMobile = ( ...

"Internet Explorer naturally selects the submit button when users press the enter key to submit a

In my current application, I have implemented a form with a hidden button to address issues with the numeric keyboard on Android. Essentially, pressing enter or focusing on the invisible button will trigger form submission. Pressing enter works fine in Ch ...

What is the best way to manage variables when iterating over an object of objects in a loop that contains inner asynchronous code?

I am working on a Node/Express server with a GET route where I need to send back a response to the client. The response consists of an array of objects, each with a 'url' property that contains a base64 encoded image retrieved using the 'bas ...

"Converting circular structure into JSON" - Inserting BigQuery Data using Cloud Function in Node.js

I am currently facing an issue while attempting to load an array of JSON objects into a BigQuery Table from a Cloud Function built in NodeJS. Despite not having any circular references, I encountered the error message "Converting circular structure to JSON ...

Prevent Purchase Button & Implement Modal on Store Page if Minimum Requirement is not Achieved

On my woocommerce shop page, I am facing an issue where all items are added to the mini-cart without meeting the minimum order requirement. This results in users being able to proceed to checkout without adding enough items to meet the minimum order amount ...

What is the best tool for syntax highlighting with Vue.js?

Looking for guidance on syntax highlighting with Vue.js. I've included the code snippet below, but for some reason the message "This is a test" isn't appearing as expected. Can someone please point out what mistake I may be making? <html> ...