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

Is it possible to implement UseState in Server-Side-Rendering scenarios?

Is it possible to utilize useState (and other react hooks?) with Server Side Rendering? I keep encountering the following error when attempting to execute the code: TypeError: Cannot read property 'useState' of null. Oddly enough, if I disable ...

Determine whether or not a selector has been designated

As I embark on developing my inaugural jQuery plugin, I aim to add a unique twist to its functionality. Let me clarify the main objective: The concept is basic - when an <input> field contains a title attribute, the input box will be pre-filled with ...

In PATCH requests, JSON data is not transmitted through Ajax

I'm attempting to send JSON data from the client to my server with the following code: $.ajax({ url : 'http://127.0.0.1:8001/api/v1/pulse/7/', data : data, type : 'PATCH', contentType : 'application/json' ...

Pictures in Windows 7 have shifted to the left

After a recent migration to the Windows 7 operating system at my company, I encountered an issue. While using the same Visual Studio 2010 master file that was working fine on my Windows XP machine, I noticed that all the images below were now shifted to t ...

Adding tween.js seems to have caused the button click event to stop triggering

After adding the code line to tween my display box, the click event is no longer triggered. There are no errors in the console. How can I resolve this issue and what might have caused it? createjs.Tween.get(directionsbox, { loop: false }).to({ x:800, y: ...

Test your word skills with the Jumbled Words Game. Receive an alert when

After reviewing the code for a jumble word game, I noticed that it checks each alphabet individually and locks it if correct. However, I would like to modify it so that the entire word is only locked if all the letters are correct. Any suggestions on how t ...

The response body from the HTTP request is consistently empty or undefined

While working with two containers managed by Docker Compose, I encountered an issue where the response body from a GET call made by a Node.js service in one container to an API in another container using the request module was consistently empty or undefin ...

Tips for keeping div and input tags selected even after a user clicks

I am working on a quiz script and I am trying to customize it so that when a user clicks on the div or input tags, they remain selected with a different background color. Currently, I have achieved changing the background color of the div when clicked, ...

Using the react-router Navigate component within a Next.js application allows for seamless

Is there a way to achieve the same result as the Navigate component in react-router within Nextjs? The next/Router option is available, but I am looking for a way to navigate by returning a component instead. I need to redirect the page without using rout ...

Unique form validation process: utilizing JSON

Attempting to validate JSON input using Angular's FormControl. The typical approach, such as validating an email address, would involve: <form name="form"> <textarea ng-model="data.email" type="email" name="email"></textarea> &l ...

Detecting when the page is done loading in CasperJS with the help of $.ajaxStop()

During my CasperJS tests, I've relied on waitForSelector() to check if a page has finished loading, including all asynchronous AJAX requests. However, I'm interested in finding a more standard approach for waiting for page load. Is it possible to ...

Error encountered: Missing class definition for `org/codehaus/jackson/JsonFactory` in java.lang package

Running an application with Restful Service and utilizing Jersey version 1.16 on a weblogic application server. The application works smoothly in the DEV server but encounters errors in the QA server, such as the following: <WLS Kernel>> <> ...

Discovering the smallest, largest, and average values across all properties in an array of objects

Given an array of objects with varying values, the task is to determine the minimum, maximum, and average of the properties in that array. For example, consider the following array: const array = [{ "a": "-0.06", "b": "0.25", "c": "-0.96", ...

Adding items to an array within a jQuery each loop and performing a jQuery ajax request

I am trying to loop through an array, push the results into a JavaScript array, and then access the data outside of each loop and AJAX call. Can anyone explain how to do this? This is what I have attempted: var ides = ["2254365", "2255017", "2254288", ...

The issue with launching a Node.js server in a production environment

I'm currently facing an issue when trying to start my TypeScript app after transpiling it to JavaScript. Here is my tsconfig: { "compilerOptions": { "module": "NodeNext", "moduleResolution": "NodeNext", "baseUrl": "src", "target": " ...

How can I efficiently transfer a JavaScript array to a PHP script using the GET method?

My web application is designed with jQuery allowing users to manipulate visual elements. The next step is sending the JavaScript object state to PHP for storage in a database. While I prefer using GET, I am open to solutions that involve POST submission as ...

The template in AngularJS route fails to display

I am currently facing an issue with loading multiple pages using AngularJS $routeProvider and two controllers. Whenever I click on a link from the first partial to go to the second one, the second partial fails to render properly, displaying only template ...

Restructuring Complex JSON Data

I have a JSON file that needs to be converted into a CSV format: [ { "key-1": "value-1", "attributes": { "trait": "name", "value": "Some value" } }, { "key-2": "value-2", "attributes": { "trait": "name", "v ...

Sending state properties to components within a route

In my React structure, I have the following setup: <Provider store={ store }> <Router> <Switch> <Route path="/how-to" component={ Help } /> <Route path="/start" c ...

Angular ensures that the fixed display element matches the size of its neighboring sibling

I have a unique challenge where I want to fix a div to the bottom of the screen, but its width should always match the content it scrolls past. Visualize the scenario in this image: The issue arises when setting the div's width as a percentage of the ...