0

An ajax response is returning json object and I want to construct a table from. The json contain the column headers in an array and the actual data in another array of dictionaries. I want the table columns to be ordered according to the array of headers:

{
    "columns": ["id", "category"],
    "data":[
      {"category": "fruit","id": 1},
      {"category": "diary","id": 2}
    ]
}



  $(document).ready(function() {
    $("#submit").click(function(event) {
      $.ajax({
        data: {
          user: $('#user').val(),
        },
        type: 'POST',
        dataType: "json",
        url: '/process'
       })
        .done(function(response) {
         if (response.error) {
          alert('Error!');
        }
        else {
          var html = '<table class="table table-bordered"><thead><tr>';
          jQuery.each(response.columns, function(index, value) {
              html += "<th>" + value + "</th>"
          })
          html += "</tr></thead><tbody><tr>"
          jQuery.each(response.data, function(index, value) {
               jQuery.each(response.columns, function(idx, col) {
                    html+="<td>" + value[col] + "</td>"
               })
          })
          html+="</tr></tbody></table>"
          $(resulttable).append(html);
        }
       });
      event.preventDefault();
     });
    });

I'm getting a table like this:

id   category
1    fruit      2     diary

instead of 

id   category
1    fruit      
2    diary

1 Answer 1

2

You need to create a new table row for each data row.

      html += "</tr></thead><tbody>"
      jQuery.each(response.data, function(index, value) {
           html += "<tr>"; //new code
           jQuery.each(response.columns, function(idx, col) {
                html+="<td>" + value[col] + "</td>"
           })
           html += "</tr>"; //new code
      })
      html += "</tbody></table>"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.