deepak murthy
deepak murthy

Reputation: 411

JSON to HTML Table in ajax

This is the JSON i have

{
   "version": "5.2",
   "user_type": "online",
   "user":
   [
       {
            "name": "John",
            "id": 50
       },
       {
            "name": "Mark",
            "id": 57
        }
    ]
}

The javascript to convert the above JSON to HTML

<script type="text/javascript">
$(document).ready(function(){
    $.ajax({
        url: "http://PATH/user.json",
        dataType: 'json',
        type: 'get',
        cache:false,
        success: function(data){
            /*console.log(data);*/
            var event_data = '';
            $.each(data, function(index, value){
                /*console.log(value);*/
                event_data += '<tr>';
                event_data += '<td>'+value.name+'</td>';
                event_data += '<td>'+value.id+'</td>';
                event_data += '<tr>';
            });
            $("#list_table_json").append(event_data);
        },
        error: function(d){
            /*console.log("error");*/
            alert("404. Please wait until the File is Loaded.");
        }
    });
});
</script>

The HTML code for table :

<table class="table table-responsive table-hover table-bordered" id="list_table_json">
    <thead>
        <tr>
            <th>Name</th>
            <th>ID</th>                  
        </tr>                   
    </thead>
</table>

Did not get any error's in the console

The output i get in the table says undefined. how to push the data to json ?

Upvotes: 4

Views: 19258

Answers (3)

user6748331
user6748331

Reputation:

This is situation where I can recommend Vue. Look for next (working) example:

var table = new Vue({
  el: '#dynamic',
  data: {
    users: []
  }
})

// And on click just assign loaded JSON to component model
// and view (table) will be re-rendered automatically
$('button').click(_ =>
  $.getJSON('https://api.mockaroo.com/api/03f2c610?count=20&key=cdbbbcd0')
   .done(data => table.$data.users = data)
)
#dynamic {
  border-collapse: collapse;
}
#dynamic th, #dynamic td {
  border: 1px solid black;
}
<script src="https://unpkg.com/[email protected]/dist/jquery.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/vue.min.js"></script>

<button>Load some fake data from mockaroo.com</button>

<!-- Prepare table in clean, readable way -->
<table id="dynamic">
  <thead>
    <tr>
      <th>ID</th>
      <th>Nick</th>
      <th>First name</th>
      <th>Last name</th>
      <th>Email</th>
    </tr>
  </thead>
  <tbody>
    <tr v-for="row in users">
      <td v-for="column in row">{{ column }}</td>
    </tr>
  </tbody>
</table>

Now, if you want this table will be sortable, its matter of few lines of code:

var table = new Vue({
  el: '#dynamic',
  data: {
    users: []
  },
  methods: {
    sort (e) { // This is the method definition
      var key = e.target.dataset.key // read data-key value from clicked th
      this.users = _.sortBy(this.users, key) // sortBy method is from underscore
    }
  }
})

// And on click just assign loaded JSON to component model
// and view (table) will be re-rendered automatically
$('button').click(_ =>
  $.getJSON('https://api.mockaroo.com/api/03f2c610?count=20&key=cdbbbcd0')
   .done(data => table.$data.users = data)
)
#dynamic {
  border-collapse: collapse;
}
#dynamic th, #dynamic td {
  border: 1px solid black;
}
#dynamic th {
  cursor: pointer;
}
<script src="https://unpkg.com/[email protected]/dist/jquery.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/vue.min.js"></script>
<!-- Underscore have some great methods for lists, array and objects -->
<script src="https://unpkg.com/[email protected]/underscore-min.js"></script>

<button>Load some fake data from mockaroo.com</button>

<!-- Prepare table in clean, readable way -->
<table id="dynamic">
  <thead>
    <tr @click="sort"><!-- Run sort method on click -->
      <th data-key="id">ID</th>
      <th data-key="nick">Nick</th>
      <th data-key="first">First name</th>
      <th data-key="last">Last name</th>
      <th data-key="email">Email</th>
    </tr>
  </thead>
  <tbody>
    <tr v-for="row in users">
      <td v-for="column in row">{{ column }}</td>
    </tr>
  </tbody>
</table>

Upvotes: 1

Moher
Moher

Reputation: 741

you must change this part of your code:

$.each(data.user, function(index, value){
    /*console.log(value);*/
    event_data += '<tr>';
    event_data += '<td>'+value.name+'</td>';
    event_data += '<td>'+value.id+'</td>';
    event_data += '</tr>';
});

Upvotes: 1

akbansa
akbansa

Reputation: 393

Your loop should be like $.each(data.user, function(index, value){}); and close </tr> in end

<script type="text/javascript">
$(document).ready(function(){
    $.ajax({
        url: "http://PATH/user.json",
        dataType: 'json',
        type: 'get',
        cache:false,
        success: function(data){
            /*console.log(data);*/
            var event_data = '';
            $.each(data.user, function(index, value){
                /*console.log(value);*/
                event_data += '<tr>';
                event_data += '<td>'+value.name+'</td>';
                event_data += '<td>'+value.id+'</td>';
                event_data += '</tr>';
            });
            $("#list_table_json").append(event_data);
        },
        error: function(d){
            /*console.log("error");*/
            alert("404. Please wait until the File is Loaded.");
        }
    });
});
</script>

Upvotes: 7

Related Questions