Christopher Allen
Christopher Allen

Reputation: 8609

JQuery JSON to table

I'm working on a project where I need to post data to a table that I receive from a query that returns JSON.

I have looked at several other posts on here about receiving JSON data and appending it to a table, but none of them have actually done the task that I need.

It's probably a good idea to mention I am new to JQUERY, but I have a fundamental understanding of what needs to happen.

My code looks like this, please note I am using a fake API to feed Chuck Norris jokes, but in the end it will feed a large number of sections that are for storing text blocks.

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<script>
$.getJSON('http://api.icndb.com/jokes/random', function(json_data){

    var table_obj = $('table');
    $.each(json_data, function(index, item){
         var table_row = $('<tr>', {id: item.id});
         var table_cell = $('<td>', {html: item.data});
         table_row.append(table_cell);
         table_obj.append(table_row);
    })

})
</script>




<table border=1>
  <tbody id="table">
  </tbody>
</table>

It appears that the query is successful and I can view the object, but it doesn't appear to create a table.

Any advice with this would be greatly appreciated.

Upvotes: 0

Views: 101

Answers (1)

Wesley Smith
Wesley Smith

Reputation: 19571

From the docs

Fetching multiple random jokes

Example:

http://api.icndb.com/jokes/random/3

Result

{
  "type": "success",
  "value": [{
    "id": 1,
    "joke": "Joke 1"
  }, {
    "id": 5,
    "joke": "Joke 5"
  }, {
    "id": 9,
    "joke": "Joke 9"
  }]
}

Therefore you need:

$.getJSON('https://api.icndb.com/jokes/random/6', function(json_data) {
  if (json_data.type = 'success') { 
    var table_obj = $('table');
    $.each(json_data.value, function(index, item) { 
         var table_row = $('<tr>', {id: item.id});
         var table_cell = $('<td>', {html: item.joke});
         table_row.append(table_cell);
         table_obj.append(table_row);
    })
  } else {
    // some error message
  }
})

Working jsFiddle

Upvotes: 1

Related Questions