0

I am new to JSON and JS, and have generated a JSON file to display data via .onclick event. I have gotten so far as generating the JSON data and displaying it on screen, but now I want to style it in a table format, where the elements are able to be seen more clearly. Any help would be awesome!

Here's my JS:

    addEventListener("load", set_up_click_handler);

function set_up_click_handler() {
  var url = 'http://localhost/Advanced_Web/Final_Project/data/exhibitions.json';
  var button = document.getElementById("button");
  button.addEventListener("click", click_handler);

  function click_handler(event) {
    var request = new XMLHttpRequest();
    request.open('GET', url);
    request.addEventListener("load", response_handler);
    request.send();

  };

  function response_handler() {
    if (this.status == 200) {
      var json = this.responseText;
      var data = JSON.parse(json);
      window.localStorage.setItem('exhibitions', JSON.stringify(data));

            var div = document.createElement("div");
            div.setAttribute("id", "dateOfExhibition");

      var list = $('<ul/>');

      for (var item in data) {
        list.append(
          $("<li />").text(item + ": " + data[item])
        );
      }
      $('#exhibitions').append(list);
    } else {
      alert('An error has occurred.');
    }
  }
    }

And if anyone is feeling extra charitable today, I'm also having this following issue: every time I click on my button, the list displays itself once again. How do I rework the code so that it only displays itself once?

  • @Paulie_D thanks for your advice, I've edited my question. – stefsrieder Mar 06 '16 at 11:44
  • OK, but it is expected that you at least attempt to code this for yourself. Stack Overflow is not a code writing service. I would suggest that you do some additional research, either via Google or by searching SO, make an attempt and. if you still have trouble, come back with **your code** and explain what you have tried and why it did not work. – Paulie_D Mar 06 '16 at 11:48
  • @Paulie_D OK, thanks for your advice. I have been attempting what I posted for exactly 3 hours, testing different approaches ranging from styling the
      elements, creating
      s that wrap around the list and styling those, researching on SO, Google, and watching YouTube videos. None of this has worked. My code is displayed above and is my most recent attempt. Any help would be appreciated.
    – stefsrieder Mar 06 '16 at 12:09
  • could you show an example of the json file you are trying to parse into a table – user2950720 Mar 06 '16 at 12:11
  • { "id": "Pavlov's Dog", "dateOfExhibition": "2018-07-08T22:00:00.000Z", "address": [], "street": "Bergmannstrasse 29", "city": "Berlin", "country": "Deutschland", "zip": "10473"} – stefsrieder Mar 06 '16 at 12:13
  • Possible duplicate of: [Convert JSON array to an HTML table in jQuery](http://stackoverflow.com/questions/1051061/convert-json-array-to-an-html-table-in-jquery?lq=1) – Yogi Mar 06 '16 at 13:08

1 Answers1

0

without really knowing the style of the table required please see the example formatting the data into a table with the headers on display, the address with an empty array also has not been handled in this function

var jsonData =  { "id": "Pavlov's Dog", "dateOfExhibition": "2018-07-08T22:00:00.000Z", "address": [], "street": "Bergmannstrasse 29", "city": "Berlin", "country": "Deutschland", "zip": "10473"};


function createTable(jsonData){ 
  //create headers
  var head = $("<tr />");    
  var keys = Object.keys(jsonData);
  keys.forEach(function(key){
    head.append($("<th>"+ key + "</th>"));
  });  
  $("#exhibitionTable").append(head);
  
  //append data (if you have multiple objects in an array like this wrap this in a forEach)
  var row = $("<tr />");    
  for (var item in jsonData){    
    row.append($("<td>"+ jsonData[item] + "</td>"));    
  }
  $("#exhibitionTable").append(row);
}


$(document).ready(function(){
  createTable(jsonData);
});
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
    <table id="exhibitionTable">
    </table>
</body>
</html>
user2950720
  • 931
  • 2
  • 10
  • 26
  • Thanks for the help! The goal is to show the table upon clicking the button triggered by click_handler. So I assume I would have to somehow attach the click handler to the createTable? – stefsrieder Mar 06 '16 at 13:10
  • on the response handler, you could have a div container for results, and inside the createTable function, create the initial table element and place it inside the container if the response is valid else show the error text – user2950720 Mar 06 '16 at 13:30
  • here is an example, using a container element to dynamically add the table https://jsbin.com/vutufaruxu/edit?html,js,console,output – user2950720 Mar 06 '16 at 13:37