4

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 ?

3
  • 4
    $.each(data,, should that not be $.each(data.user,? Commented Sep 14, 2017 at 10:19
  • 1
    Careful, in your loop, you're not closing your <tr> after adding your two <td> Commented Sep 14, 2017 at 10:23
  • thanks for reminding the closing tag </tr> Commented Sep 14, 2017 at 10:33

3 Answers 3

7

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>
Sign up to request clarification or add additional context in comments.

6 Comments

thanks. worked well, what if in the JSON { "version": "5.2", "user_type": "online", "user": [ { "name": "John", "id": 50, "last name":"A" }, { "name": "Mark", "id": 57 "last name":"B" } ] } how do i add "last name" into the table. it has a space
$.each(data.user, function(index, value){ /*console.log(value);*/ event_data += '<tr>'; event_data += '<td>'+value.name+" "+value.last_name+'</td>'; event_data += '<td>'+value.id+'</td>'; event_data += '</tr>'; });
Because your json has key "last name" try getting key as "last_name" or "lastName" as use accordingly in <td>
is there a way to access "last name" without changing the json
Then you can use like value["last name"]
|
1

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

Comments

1

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>

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.