Two consecutive instances of the outcome recorded in the ajax table

I am trying to add data to a table, but one of my results is appearing twice. Here is the JSON response I received:

groupname   […]
 0  {…}
 survey_id  2
 group_name DEMO
 1  {…}
 survey_id  1
 group_name TEST

This is what my AJAX success function looks like:

if(data){

    var txt = "";
    for(var i=0;i<=Object.keys(data).length;i++){
    if(data ){
      txt += '<tr><td>'+data.groupname[i].group_name+'</td></tr>';
             }
    if(txt != ""){
            $("#table").append(txt);
                 }

            }
       }

However, when displayed, it shows duplicate entries as seen in the following image: https://i.stack.imgur.com/sMyQc.png

I am looking to display only one DEMO and one TEST entry.

Answer №1

txt+ function will also include the previous value. Ensure to verify if data.groupname[I].group_name is not empty before adding a new row to the table.


if(data){
    var txt = "";
    for(var i=0;i<=Object.keys(data).length;i++){
    //txt+ function will also append the previous value. So, make sure to check if data.groupname[i].group_name is not empty before appending.
    if(data.groupname[i].group_name ){
        txt = '<tr><td>'+data.groupname[i].group_name+'</td></tr>';
        $("#table").append(txt);
    }
    }
}

Answer №2

To solve the issue, ensure that you append after the for loop instead of collecting and appending within each index of the loop. Instead, gather all the rows first and then append them together.

if(data){
    var txt = "";
    for(var i=0;i<=Object.keys(data).length;i++){
      if(data ){
        txt += '<tr><td>'+data.groupname[i].group_name+'</td></tr>';
      }
    }
    if(txt != ""){
      $("#table").append(txt);
    }
 }

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

What is the purpose of sorting an object using the sequence defined in an array?

Have you ever wondered how the sortWeekFunction function can rearrange an object based on a predefined array order? It may seem complex at first glance, but let's break down how this code actually works. const weeksArr = ['sunday', ' ...

Avoiding duplicate clicks in Onsen UI Navigator.Avoid duplicate clicks in

When a user clicks on an item in my list, they are taken to a details page. However, if the user clicks too quickly, two click events may be fired, leading them to navigate to two different pages consecutively. Is there a way to prevent this issue? Can we ...

How can we generate 3 different arrays, each containing an equal number of items except for the last array, using VueJS?

Incorporating Bootstrap5 and VueJS 2, I am working on designing a layout of cards in a "pinterest-style" arrangement, as depicted in the following screenshot: https://i.sstatic.net/AvdWR.png To achieve the layout showcased above, the HTML markup required ...

What is the best way to prompt Leaflet to refresh the map display?

I'm facing a challenge while integrating Leaflet with React, where Leaflet seems to want control over the DOM rendering as well based on my research. Currently, I have countries being properly colored according to specific color codes derived from ba ...

Can you locate the hiding spot of the express-session cookie?

After setting a very short cookie max-age (10 secs) in my express-session, I confirmed that it is working as expected: app.use(session({ secret: 'xxx', resave: false, saveUninitialized: true, cookie: { secure: true, maxAge: 10000 } })); ...

What is the best way to extract data from a text file that contains multiple data entries separated by pipes (|) using the fs module?

I'm currently utilizing the node.js fs module to read a text file. One thing that I'm wondering is, does the fs module only support reading text files or can it handle other file formats as well? Now, my primary inquiry is if the text file conta ...

Discover the method to retrieve the chosen value from a list of radio buttons using AngularJS

After making an AJAX request and receiving JSON data, I have created a list of radio buttons with values from the response. Although I have successfully bound the values to the list, I am facing difficulty in retrieving the selected value. Below is a snipp ...

Unfortunately, we encountered an AJAX error while trying to access data from the website datatables.net. You can find

I'm currently working on adding data to a datatables.net datatable using a JSON response, following the example provided here. To achieve this, I am making use of an AJAX call to fetch a JSON response from a database. After obtaining the data, I uti ...

Is there a different method to retrieve language bundles with next-i18next instead of using a customized Node server?

Currently, I am developing a Next.js application that will utilize i18next translations organized in the recommended file structure for bundles. For example: static/locales/en/common.js static/locales/de/common.js You can refer to this article: https://m ...

Problems with spacing in Slick slider and lazyYT integration

Utilizing lazyYT helps to enhance the loading speed of YouTube videos. Once loaded, these lazyYT videos are then placed within a slick slider. However, an issue arises where the videos stick together without any margin between them. To address this problem ...

What causes an infinite loop in my app when passing a prop, and why doesn't it update the prop as expected?

Trying to pass a single variable from one component to another should be simple, but it's turning out to be more complicated than expected. I have a Search bar in one component and I want the input from that search bar to display in another component. ...

Obtaining only a portion of the text when copying and editing it

I have a React application where I am attempting to copy text from an HTML element, modify it, and then send it back to the user. I have been successful in achieving this, but I am facing an issue where even if I select only a portion of the text, I still ...

Utilizing Multiple Checkboxes for Precision Search Refinement

Big thanks to Khalid Ali for the support provided up until now. I am currently working with an array of songs that each have descriptions, keywords, etc. I have a set of checkboxes that I want to use to refine a search. Essentially, if someone selects the ...

Is it really necessary to still think poorly of JavaScript in 2011?

Here's an intriguing question for you. I've tested out a variety of popular websites, including Facebook, and I've noticed that many features still work perfectly fine even when JavaScript is disabled. People always used to say that JavaScr ...

What is the best way to display a list of lists in a React application?

I have a collection of lists containing data that I need to display on the view. The data: { "blocks_content": [ [ " Bakery", " Company GbR", ], [ ...

Could you kindly explain what the issue is with the JSON.parse error?

Upon testing this code, an error was reported by firebug: SyntaxError: JSON.parse: unexpected character at line 2 column 1 of the JSON data. Due to my limited knowledge in json, I couldn't pinpoint the source of the error on my own. Could you please ...

What are the best plugins and projects to maximize IntelliJ IDEA's potential for JavaScript development?

I am currently in the process of developing a web application utilizing the MEAN stack: MongoDB, Express, Angular, and Node.js. The foundation of my project is built upon Daftmonk's angular-fullstack Yeoman generator. Despite my primary experience be ...

The functionality of core-ui-select is not functioning properly following the adjustment of the

I've implemented the jquery plugin "core-ui-select" to enhance the appearance of my form select element. Initially, it was functioning perfectly with this URL: However, after applying htaccess to rewrite the URL, the styling no longer works: I&apos ...

What is the best way to visually refresh a polymer element that displays data from a frequently changing URL?

Hey there! I'm currently facing an issue with displaying a polymer element that contains some important information. This element is supposed to appear when I tap on an icon, but for some reason it doesn't show up even after the data has been loa ...

Using JavaScript Object Constructor to alter text color

Seeking some guidance as a newbie here on how to deal with a problem I'm currently tackling. I understand that using an object constructor may not be the most efficient way to handle this, but I'm eager to enhance my knowledge of objects. My quer ...