How to append jquery stringyfy data to table with editable (tr and td) data of 4 users one by one like loop

Viewed 74

I am getting json.stringyfy data and want to append all json.stringyfy data to table,with each tr editable but I don't know that much part of jquery so unable to get any idea can anyone tell me what should do to achieve this?

Json data got in response

[{"id":"1","name":"abc"},     user  id 1 data
{"id":"2","name":"def"},      user  id 2 data
{"id":"3","name":"xyz"},      user id 3 data
{"id":"4","name":"aaa"}]      user id 4 data

Ajax call with success function to handle stringyfy data

$.ajax({
            url: "<?= base_url('Test_controller/show_user') ?>",
            type: 'POST',
            data: {
            },
            success: function (response) {
                var myJSON = JSON.stringify(response);
// code Here  to append data in table one by one with content editable tr

            }
        });

Html table

<table class="show_data">
     <tr>
          <th>User id</th>
          <th>User name</th>
     </tr>
</table>
2 Answers

Just take your data and append it to the table. Loop through each entry in your data and (if using jquery) do .append(). I just create a simple variable with your json but you can do this with your myJSON variable inside of the success function.

var data = [{"id":"1","name":"abc"},
{"id":"2","name":"def"},  
{"id":"3","name":"xyz"},
{"id":"4","name":"aaa"}]


data.forEach(user => {
    $('.show_data').append(`<tr><td>${user.id}</td><td>${user.name}</td></tr>`);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="show_data">
     <tr>
          <th>User id</th>
          <th>User name</th>
     </tr>
</table>

Edit

You are getting that in error because you are using JSON.stringify which makes your json a string. You can't iterate on a string. Just use response instead of JSON.stringify(response);

You may use jQuery.each() and build elements on the fly:

var myJSON = [{"id": "1", "name": "abc"},
    {"id": "2", "name": "def"},
    {"id": "3", "name": "xyz"},
    {"id": "4", "name": "aaa"}];
$.each(myJSON, function (idx, ele) {
    $('.show_data tbody').append(
            $('<tr/>')  // create a TR
            .append($('<td/>', {text: ele.id})) // append the first TD
            .append($('<td/>', {text: ele.name})) // append the second TD
    );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table class="show_data">
    <thead>
    <th>User id</th>
    <th>User name</th>
    </thead>
    <tbody>
    </tbody>
</table>

Related