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

"Trying to access the Reducer in a container results in an undefined value

I recently tried adding a new Container to my React App, connected it with Redux, and wanted to test if everything was functioning properly. Unfortunately, when I try to access the reducer using this.props.selection, it returns as undefined. This is puzzli ...

CSRF protection error in Laravel when attempting to delete data using Ajax

Having trouble deleting data from a database using an ajax call due to an error that keeps popping up. Encountering a CSRF token mismatch issue In the header: <meta name="csrf-token" content="{{ csrf_token() }}"> In the blade template: <but ...

I am having trouble retrieving the array value from the response sent by my server

After receiving a dictionary from my server, when I try to access the values using the following code: {"filters":{ "Facture": [ "Магма (Тычок)", "Тонкий кирпич", "Гладк ...

Joomla page experiencing JSON encoding issue related to RokSprocket plugin

I have a Joomla plugin called RokSprocket that loads all my Joomla articles from a table. The issue I'm facing is that I have approximately 80 articles, and initially only 10 of them are shown upon loading with a button to load more. When I click the ...

Using Jquery.Ajax to send a pair of arguments to a POST api请求

My controller method has the following structure: [HttpPost] public HttpResponseMessage SaveFunc(ChangeRequest[] changeRequests, string comment) { //perform actions } In this method, a user can save a set of changerequ ...

What are the steps to successfully submit my form once all the validation requirements have been met?

I successfully completed the validation process, but I am encountering an issue when trying to submit the form. An error message pops up indicating that there is an error related to a specific field (e.g., special characters being used). However, even when ...

Method for transmitting JSON array from Controller to View using CodeIgniter

I have a function in my controller: function retrieveAllExpenses() { $date=$this->frenchToEnglish_date($this->input->post('date')); $id_user=$this->session->userdata('id_user'); $where=array('date&ap ...

What is the method to retrieve a JSON encoding from the render function in Symfony2?

Struggling to implement ajax in symfony, as it poses a challenge. There's a form in twig where a value is obtained for searching a product in the database: This is the form in twig: <form id="myForm" method="post" action="{{ path('my_app_gre ...

Invoking Ajax within a for loop

for (var i = 0; i < 5; i++) { using (x = new XMLHttpRequest()) sendRequest("GET","d.php?id=" + i), checkResponse(null), updateStatus = function() { if (x.state == 4 && x.responseCode == 200) notifyUser(i); } } My goal now is to e ...

The scrolling speed of the mousewheel in Firefox is notably slower compared to that of Google Chrome

Kindly review this sample link: When I test the above example in Chrome and scroll using the mouse wheel, the page moves up by 100px each time. The Y position is displayed as well. However, if I try the same page in Firefox 26.0 and scroll with the mouse ...

Unable to send a value to a CodeIgniter controller using AJAX

I am attempting to create an update function using ajax with two parameters that need to be passed to my CI controller. However, I encountered an error and suspected that the parameters were not being correctly passed to the controller. Below is the ajax ...

Using API JSON, fill the second dropdown list based on the selection made in the first dropdown

I need help in populating data in the 2nd drop-down list based on the selection made in the 1st drop-down list. I am currently using AJAX to fetch and display the data in the 2nd drop-down list. Below is the JSON output when facID = F09: Here is the AJAX ...

Encountering an error message that says "ERROR TypeError: Cannot read property 'createComponent' of undefined" while trying to implement dynamic components in Angular 2

I am currently facing an issue with dynamically adding components in Angular 4. I have looked at other similar questions for a solution but haven't been able to find one yet. The specific error message I am getting is: ERROR TypeError: Cannot read ...

Utilizing AngularJS to connect a dynamic result array to a table with varying layouts

I am struggling to bind a dynamic array result with a table using Angular JS in a different layout. Despite multiple attempts, I have not been successful in achieving the desired outcome. Any help or guidance would be greatly appreciated. var arr = [ ...

Typescript Routing Issue - This call does not match any overloads

Need assistance with redirecting to a sign-up page upon button click. Currently encountering a 'no overload matches this call' error in TypeScript. Have tried researching the issue online, but it's quite broad, and being new to Typescript ma ...

The art of encapsulating JSON response objects in Ember Objects with a deep layer of wrapping

Currently, I am engaged in a project using Ember where I retrieve a complex JSON response in a Route's model function. In the associated template, I exhibit attributes of the response. Some of these attributes allow for specific actions that result in ...

Ways to choose an element when all classes are identical but the text content varies?

I'm looking to automate the website, specifically by selecting the Widgets section and clicking on it. The issue is that all the cards have the same class name, only the text inside them differs. I tried using this code snippet: get getWidgetButton() ...

transferring iterative information via ajax data flow

My form includes hidden input fields that are manually declared in the AJAX data without a loop. How can I efficiently loop through them in the AJAX data? Below is my form script: <form method="POST" name="myform"> <?php for($i=1;$i<=5;$i+ ...

How can I leverage Express, AngularJS, and Socket.io to facilitate broadcasting and receiving notifications?

A new notification system is in the works. To illustrate, User 1 is initiating a friend request to User 2. The technologies being utilized include express.js, angularjs, and socket.io. When User1 clicks the button, a request is sent. On User2's end, a ...

Using Javascript's .replace() method to preserve HTML elements

This is a JavaScript function I wrote function replaceCharacters(text_input){ return text_input .replace(/O/g, 0) .replace(/I/g, 1) .replace(/o/g, 0) .replace(/i/g, 1) .replace(/t/g, 4) .replace(/d/g, 9) ...