onlyforbopi
9/27/2018 - 7:13 AM

JS.JSON.DynamicTable.Dynamic Table built from Remote Data (using JSON and fetch)

JS.JSON.DynamicTable.Dynamic Table built from Remote Data (using JSON and fetch)

button{
  background-color: indigo;
  color: white;
  font-size: 15px;
  padding: 5px;
  margin-left: 40%;
  width: 20%;
}

button:hover {
  background-color: #76E5FC;
}

table {
  margin-left: 15%;
  width: 70%;
  border-collapse: collapse;
}

caption {
  margin-top: 10px;
  color: white;
  background-color: indigo;
  font-size: 25px;
  padding: 2px;
}

tr {
  background: #EBDEF9;
  border: 1px solid black;
  text-align: left;
  color:black;
}

tr:nth-child(even) {
  background: #F4ECF1; 
}

tr:hover {
  background: #76E5FC;
}

td {
  padding-left: 5px;
}
function search() {
  var queryURL =
  "https://gist.githubusercontent.com/heiswayi/7fde241975ed8a80535a/raw/ff1caaeaf62bd6740ab7cafcd61f1215de173379/datatables-data.json";

  fetch(queryURL)
    .then(function(response) {
      // response.json() returns a json string,
      // returning it will convert it
      // to a pure JavaScript
      // object for the next then's callback
      return response.json();
    })
    .then(function(users) {
      // users is a JavaScript object here
      displayUsersAsATable(users);
    })
    .catch(function(error) {
      console.log("Error during fetch: " + error.message);
    });
}

function displayUsersAsATable(users) {
  var div = document.querySelector("#users");
  var table = document.createElement("table");
  table.classList.add("table");
  var caption = table.createCaption();
  caption.innerHTML = "Data";

  var header = table.createTHead();
  var row = header.insertRow();
  row.style = "color: white; background-color: indigo; font-size: 20px; border-top: none;"

  var cell1 = row.insertCell(0);
  cell1.innerHTML = "Name";
    var cell1 = row.insertCell(1);
  cell1.innerHTML = "Job";
    var cell2 = row.insertCell(2);
  cell2.innerHTML = "Location";
    var cell3 = row.insertCell(3);
  cell3.innerHTML = "Age";
    var cell4 = row.insertCell(4);
  cell4.innerHTML = "Date";
    var cell5 = row.insertCell(5);
  cell5.innerHTML = "Salary";

  var length = users.data.length;

  for (var i = 0; i < length; i++) {
    var rows = table.insertRow();
    var cells = users.data[i].length;
    for (var x = 0; x < cells; x++) {
      var cell = rows.insertCell();
      var txt = users.data[i][x];

      cell.innerHTML = txt;
    }
  }
  div.appendChild(table);
}

JS.JSON.DynamicTable.Dynamic Table built from Remote Data (using JSON and fetch)

A Pen by Pan Doul on CodePen.

License.

<html lang="en">
<head>
<title>Working with remote data via JSON</title>
  <meta charset="utf-8"/>
  <!-- Polyfill in case your browser does not support the fetch API -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fetch/0.10.1/fetch.js"></script>

</head>
<body>
  <button onclick="search();">Get a Remote List of Data</button>
  <div id="users"></div>
</body>
</html>