Ad

Result Appended Twice To Table Ajax

- 1 answer

I am tring to append data to a table. But one of my result is repeating twice. Below is my json response I got.

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

My ajax success is as follows

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);
                 }

            }
       }

But it displays as below

img

I need only 1 DEMO and 1 TEST

Ad

Answer

txt+ will append the previous value also. check if data.groupname[I].group_name is not empty, then appended the row in table.

if(data){
    var txt = "";
    for(var i=0;i<=Object.keys(data).length;i++){
    //txt+ also will append the previous val. SO check if data.groupname[i].group_name is not empty then append.
    if(data.groupname[i].group_name ){
        txt = '<tr><td>'+data.groupname[i].group_name+'</td></tr>';
        $("#table").append(txt);
    }
    }
}
Ad
source: stackoverflow.com
Ad