Populating a table with information retrieved from a file stored on the local server

Here is the specific table I am working with:

<div class="chartHeader"><p>Performance statistics summary</p></div>
<table id="tableSummary">
    <tr>
        <th>Measurement name</th>
        <th>Result</th>
    </tr>
    <tr>
        <td>Total messages sent</td>
        <td id = "totalMessagesSent"></td>
    </tr>
    <tr>
        <td>Total messages processed</td>
        <td id = "totalMessagesProcessed"></td>
    </tr>
    <tr>
        <td>Average messages per second</td>
        <td id = "averageMessagesPerSecond"></td>
    </tr>
</table>

I have a JSON file generated in Groovy stored somewhere on my disk:

{
    "reportSummary": {
        "totalMessagesSent": 23,
        "totalMessagesProcessed": 10384,
        "averageMessagesPerSecond": 2.3E-8
    }
}

I've been trying to populate the table above with data from this JSON using JavaScript, but so far I haven't been successful. In my HTML page, I have added:

<script type="text/javascript">fillTableWithData('reportSummary.json');</script>

Currently, my script looks like this, but it's not functioning as intended:

function fillTableWithData(filename) {
    var reader = new FileReader();
    var jsonFile = reader.readAsText(filename);
    var jsons = d3.json(jsonFile);

    d3.select("#totalMessagesSent").append(jsons.totalMessagesSent);
    d3.select("#totalMessagesProcessed").append(jsons.totalMessagesProcessed);
    d3.select("#averageMessagesPerSecond").append(jsons.averageMessagesPerSecond);
}

If anyone has suggestions on how to correctly achieve this task, please let me know. I've spent a lot of time on it and I'm currently out of ideas. Thank you in advance for your help.

EDIT: If it's easier to do it in pure JS, I don't necessarily need to use d3 for this task...

Answer №1

Look no further for the solution to that issue:

function loadDataIntoTable(file) {

var dataFile = file;
var httpRequest = new XMLHttpRequest();
try {
    httpRequest = new XMLHttpRequest();
} catch (error) {
    try {
        httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (error) {
        try {
            httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (error) {
            alert("Oops, looks like your browser is having issues!");
            return false;
        }
    }
}
httpRequest.onreadystatechange = function () {
    if (httpRequest.readyState == 4) {
        var jsonData = JSON.parse(httpRequest.responseText);

        document.getElementById("messagesReceived").innerHTML = jsonData.reportSummary.messagesReceived;
        document.getElementById("eventsProcessed").innerHTML = jsonData.reportSummary.eventsProcessed;
        document.getElementById("averageEventsPerSecond").innerHTML = jsonData.reportSummary.averageEventsPerSecond;
    }
}
httpRequest.open("GET", dataFile, true);
httpRequest.send();
}

Keep in mind, using JavaScript alone won't suffice for loading files since it operates on the client's end.

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 'data' variable is not defined in the React custom hook Pagination

I am currently working with an API that shows music categories on a browser, and I'm attempting to create a custom pagination hook. However, I keep encountering an error stating "object is not iterable." I am new to custom hooks and would appreciate a ...

What is the best way to ensure a DOM element exists before you can start manipulating it?

In my AngularJS application, I am utilizing Angular Material and md-select. When a user clicks on the md-select, a dropdown list appears and an overlay with the tag Name is added to the DOM. My goal is to add a class or style as soon as the user clicks on ...

Creating a structure within a stencil web component

In my current project, I am utilizing Stencil.js (typescript) and need to integrate this selectbox. Below is the code snippet: import { Component, h, JSX, Prop, Element } from '@stencil/core'; import Selectr from 'mobius1-selectr'; @ ...

Using Rails: How to invoke a function in the asset pipeline from a JS response?

In one of the JavaScript files I am working with, I have defined an object and a function: chosen.coffee Foo = do_this: -> $('.slider').slider() $ -> Foo.do_this() This code initializes JQueryUI to turn a specific div into a ...

What causes the lack of impact on lambda rendering speed despite integrating webpack?

Hey there, I've been working on implementing webpack for a project that involves microservices, Node.js, TypeScript, AWS, and AWS SAM. My main objectives are: Reduce the cold start time of lambda functions. Minimize security vulnerabilities by e ...

Problem with Ionic 2 local storage: struggling to store retrieved value in a variable

Struggling to assign the retrieved value from a .get function to a variable declared outside of it. var dt; //fetching data this.local.get('didTutorial').then((value) => { alert(value); dt = value; }) console.log("Local Storage value: " ...

What is the method to retrieve a randomly generated class from an id?

Is there a way to target elements that have the class "my_class" within the element with the id of "info_id"? It's important to note that these elements may also have another class, which I'm not interested in selecting. <div id="info_id"> ...

Protractor and Jasmine fail to fulfill the promise of retrieving a webpage title

I am facing an issue with my protractor/jasmine test code where it only prints out 1 and 2, then hangs and times out. It seems like there might be a problem with the click() action on the button element or the promise on the getTitle method of the browser ...

Enhancing parent component props in React-router-dom: A guide to updating them

Here is the structure of my App component: const App = (props) => ( <BrowserRouter> <PageTheme {...some props I'd like to change on route change}> <Switch> <Route exact path="/example"> <E ...

Utilizing Slim PHP to generate JSON responses

I have a situation where my backbone application is making an ajax GET call to my slim php app, expecting JSON dataType in return. $.ajax({ url: './myroute', type: 'GET', dataType: "json", data: { userna ...

Clones are made sortable instead of arranging them in a specific order

I have a list that can be sorted with some customizations. However, I am facing an issue where the items in the list get duplicated every time I try to sort them. When I pull one item to sort it, another copy gets added automatically. I am struggling to u ...

Ways to switch text on and off smoothly using transitions

I have created a webpage where text starts off hidden but has a visible heading. When you click on the heading, the text is revealed below. I am putting the final touches and aiming to make the text slide in smoothly. I am using Javascript for toggling ins ...

Which library do you typically employ for converting .mov files to mp4 format within a React application using Typescript?

As a web programming student, I have encountered a question during my project work. In our current project, users have the ability to upload images and videos. Interestingly, while videos can be uploaded successfully on Android devices, they seem to face ...

The CORS middleware seems to be ineffective when used in the context of Node.js

I have set up my REST API on a Raspberry Pi server and connected it to the public using localtunnel. I am trying to access this API from a localhost Node.js application. The Node application is running on Express and includes some static JS files. However, ...

Using PHP and JSON to successfully store JSON data in a MySQL database

My PHP script is encountering an issue where it only displays some of the JSON output when trying to insert it into a MySQL database. Below is the code snippet: $json = json_decode(file_get_contents('data.json'), true); $data = $json; // Varia ...

Is it appropriate to use a component inside an entry component?

I'm currently working on a component that triggers a function to open a window: @Component({ selector: 'app-deposits', templateUrl: './deposits.component.html', styleUrls: ['./deposits.component.scss&apo ...

Is Webpack CLI causing issues when trying to run it on a .ts file without giving any error

I am facing an issue with my webpack.config.js file that has a default entrypoint specified. Here is the snippet of the configuration: module.exports = { entry: { main: path.resolve('./src/main.ts'), }, module: { rules: [ { ...

The imported package is not functioning properly within the project

I've recently developed a Typescript Package and I want to test it in an application before publishing it on NPM. The main file (index.ts) of the package is structured like this => import Builder from './core/builder'; export default ...

Having trouble with the menu toggle button on Bootstrap 4?

When using Bootstrap 4, the breadcrumb button may not function properly when the header becomes responsive. I have ensured that Bootstrap 4 CSS and JS are included in the project. Please assist me in resolving this issue. Code: .navbar { height:100 ...

I'm experiencing an issue with Gravity Forms validating hidden fields, is there a solution for this problem?

On my webpage, there are four fields labeled A, B, C, and D. Each field has its own set of conditional logic that determines whether it should be visible or hidden. Let's say a user lands on this page and only field B is displayed while the others are ...