Tips for enhancing the presentation of JSON information

I recently ventured into the world of JSON and JS, managing to create a JSON file to showcase data using .onclick event. While I have successfully generated and displayed the JSON data on screen, my next goal is to present it in a table format for better clarity. Any assistance would be greatly appreciated!

Below is the snippet of my JS code:

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

If you're feeling generous today, I'm also facing an issue where clicking the button causes the list to display itself repeatedly. How can I modify the code to ensure it only displays once?

Answer №1

Uncertain of the required table style, the data has been formatted into a table with headers displayed. Note that the address field, containing an empty array, is not handled by 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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The sorting feature for isotopes is malfunctioning following the addition of a new div element

Isotope was utilized for sorting divs based on attribute values, however, a problem arises when a new div is added or an existing div is edited. The sorting functionality does not work properly in such cases, as the newly created or edited div is placed at ...

Saving data to a database using jQuery Ajax when multiple checkboxes are checked

Looking for a solution to store checkbox values into a database using jQuery Ajax to PHP. To see a live demo, click here. The image above illustrates that upon checking certain checkboxes and clicking Update, the checkbox values along with their IDs will ...

Encountering a high volume of requests error while attempting to retrieve data from the API using the NodeJS backend, yet functioning properly on the React

While attempting to retrieve data from https://api.solscan.io/chaininfo using a NodeJS backend application, I encountered an error stating 429: Too many requests. Interestingly, the same API functions without any issues when utilized in a React frontend a ...

Loading information from JSON document using AJAX

I am currently in the process of developing a sports website and I need to retrieve JSON data from . To achieve this, I have implemented an ajax call in my page with the following script: <div id="data"></div> <script> $.ajax({ ...

Adjustable slider height in WordPress

Struggling with the height of the slider on my website. I've tried various CSS adjustments and even tweaked the Jquery, but it still doesn't display properly on mobile devices. For instance, setting a height of 300px looks perfect on desktop brow ...

The GET method for accessing JSON data is now eliminating any leading zeros in the

When attempting to utilize jQuery to send the string "0002" to a WebMethod, I am encountering an issue where the leading zeros are being removed. $.ajax({ type: "GET", url: "CallNote.aspx/GetStoreRegion?storeCode=0002", contentType: "application/jso ...

The Jquery instructions were not executed

Enjoy your day! I have recently downloaded the latest compressed version of jQuery from a lesson site here (Download the compressed, production jQuery 3.6.0) After that, in my HTML document, I included it like this: <head> <meta charset = &qu ...

"Converting JSON data from a formatted JSON content to a JSON string within an Apex environment

I used a JSONGenerator object named gen to create JSON-encoded content. The resulting JSON string generated by the code snippet below is automatically formatted for readability: gen.getAsString(); However, I need to convert this prettified JSON string ba ...

What is the best way to include the Mailchimp integration script in the `Head` of a Next.js project without causing any pre

Hello there Incorporating mailchimp integration into my nextjs site is proving to be a challenge. I've been attempting to add the following code snippet to next/Head within my custom _document <script id="mcjs">!function(c,h,i,m,p){m= ...

Issue: Connection Problem in React, Express, Axios

I've encountered an issue while attempting to host a website on an AWS EC2 instance using React, Express, and Axios. The specific problem I'm facing is the inability to make axios calls to the Express back-end that is running on the same instanc ...

What is the most effective method for executing functions in a step-by-step manner, starting from 1,

var container = $("div"); firstFunction(), secondFunction(), thirdFunction() function firstFunction() {container.css("background", "#f00").hide().fadeIn(1000)}; function secondFunction() {container.css("background", "#ff0").hide().fadeIn(1000)}; function ...

Revise the Event Handlers as the DOM structure evolves

Similar Question: Tracking DOM changes in JavaScript I am working with backbone.js and dynamically generated templates. In addition, I am utilizing multiple jQuery UI plugins that interact with specific classes, such as slimScroll: $(function(){ $(& ...

Is it possible to place Angular Material components using code?

Currently, I'm in the process of creating a responsive Angular application. Is there any way to adjust the height and position of the <mat-sidenav-content></mat-sidenav-content> component in Angular Material programmatically without relyi ...

Issues with rendering Vue 3 component, visible in the elements tree but not displaying on the screen

Recently, I delved into Vue to update one of my components with the new syntax in order to grasp Vue 3 better. However, after the modifications, the component that had been functioning perfectly before now seems to be failing to render properly. The origi ...

Ensure that the input field requires the first letter to be capitalized and the subsequent letters to be in lowercase

There are numerous ways to capitalize the first letter and make the rest lowercase on Stack Overflow. However, I am looking for a method that can instantly enforce this rule in the input field. Being new to AngularJS, I am currently working with version 1 ...

What is the process for resetting a JQueryUI effect animation?

I'm facing an issue with two timer bars that each wind down over a 5-second period. When I try to stop and reset the first timer, it simply continues from where it left off instead of resetting. The desired behavior is as follows: Timer1 starts User ...

Guide to transforming Excel formulas into JavaScript

In my Excel sheet, I have the following formula: =IF($F6=0,"",IF(I6=0,"",$F6/I6)) where F6=7000 and I6 is empty. The Excel result is displaying no data for the formula. Now, I need to convert this formula into JavaScript. function AB6(F6) { var ...

Utilizing JSON and Javascript to dynamically generate and populate interactive tables

Here's how I've structured my JSON data to define a table: var arrTable = [{"table": "tblConfig", "def": [{"column": "Property", "type": "TEXT NOT NULL"}, {"column": "Value", "type": "TEXT NOT NULL"}], "data": [{"Property ...

Gradient background overlaid with a blended SVG shape

Creating a full gradient background with a clipping mask can be tricky. I used an SVG to achieve the desired shape by cutting part of the background color, but now I'm facing a challenge with blending the colors seamlessly. I tried setting the SVG co ...

"Click to view the latest data visualization using the Chart.js

I am exploring ways to enhance the animations in Chart.js for a new web project. The content is organized in tabs, with the chart displayed on the third tab out of four. Currently, the chart animates upon loading. How can I make it so that when #chartTrig ...