What is the best method for adding a JSON array with objects to an already existing table?

After incorporating Bootstrap into my HTML file, I designed a basic table. To populate this table with data from an external JSON file upon clicking a button, I utilized XMLHttpRequest and JSON.parse successfully. However, I encountered difficulties when trying to insert the parsed data into the table using my append_json function in the script below.

Any assistance would be greatly appreciated :)

Below is the structure of my table:

<table class="table table-bordered table-hover" id="table">
    <thead class="thead-dark">
        <tr>
            <th scope="col">#</th>
            <th scope="col">Name</th>
            <th scope="col">Quantity</th>
            <th scope="col">Price</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th scope="row">1</th>
            <td></td>
            <td></td>
            <td></td>
        </tr>
        <tr>
            <th scope="row">2</th>
            <td></td>
            <td></td>
            <td></td>
        </tr>
        <tr>
            <th scope="row">3</th>
            <td></td>
            <td></td>
            <td></td>
        </tr>
    </tbody>
</table>  

This is the current status of my JavaScript:

<script>
    var btn1 = document.getElementById("btn1");
    var btn2 = document.getElementById("btn2");

    btn1.addEventListener("click", function (){
        var request = new XMLHttpRequest();

        request.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                var json = request.response;
                var data = JSON.parse(json);

                append_json(data);
            }
       };

       request.open("GET", "products.json", true);
       request.send();
   })

   function append_json(data) {}
</script>

Here is the excerpt from the JSON file:

  {
     "products": [
    {
        "id": "1",
        "name": "Apples",
        "hasQuantity": "100",
        "price": "3.10"
    },
    {
        "id": "2",
        "name": "Pears",
        "hasQuantity": "50",
        "price": "2.50"
    },
    {
        "id": "3",
        "name": "Bananas",
        "hasQuantity": "100",
        "price": "2.01"
    },
    {
        "id": "4",
        "name": "Tangerines",
        "hasQuantity": "150",
        "price": "3.41"
    },
    {
        "id": "5",
        "name": "Plums",
        "hasQuantity": "50",
        "price": "4.11"
    },
    {
        "id": "6",
        "name": "Straberries",
        "hasQuantity": "50",
        "price": "3.07"
    }
    ,
    {
        "id": "7",
        "name": "Watermelon",
        "hasQuantity": "20",
        "price": "2.19"
    }

  ]
 }

Answer №1

If you need to convert JSON into an array, simply use the following code snippet:

var myArr = JSON.parse(data);

You can then access the array just like any regular array:

myObj = myArr[1]

To add the data using insertRow and insertCell functions, follow this example:

  var table = document.getElementById("table");
  var row = table.insertRow(0);
  var cell = row.insertCell(0);
  cell.innerHTML = "Cell data here";

Of course, you will need to loop through the parsed data and replace [1] with [i]. You should be able to do this on your own.

EDIT:

Here is an example of how you can achieve this:

 var table = document.getElementById("myTable");

for( var i = 0; i < myArr.length ; i++) {
  var myObj = myArr[i]
  var row = table.insertRow(i);
  var cell1 = row.insertCell(0);
  var cell2 = row.insertCell(1);
  var cell3 = row.insertCell(2);
  cell1.innerHTML = myObj.name;
  cell2.innerHTML = myObj.quantity;
  cell3.innerHTML = myObj.price;
  }
}

Best of luck!

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

What is the best location to integrate Swagger-UI in a Rails application using Grape?

I'm in the process of revamping a Rails application that heavily relies on APIs, utilizing Grape by Intridea and grape-swagger gem to incorporate Swagger UI for documentation. Currently, I have a basic hello world app up and running. It appears to be ...

What impact do the input values of an Angular reactive form have on the DOM?

I am currently working on developing a UI wizard app using Angular (reactive forms) version 6/7. The main purpose of this app is to enhance the product page of an ecommerce platform such as Shopify or WordPress. I am utilizing angular material radio inputs ...

Dynamically obtaining the screen width in JSP using a variable

Could someone provide assistance on how to resize an image using an img src="blah.jpg?width=x" so that my page can be displayed at various sizes? I just need x (width) as a JSP variable. Update 2021: It's been 9 years since this question wa ...

Unable to achieve successful HTML file upload using jQuery/Ajax

I've been attempting to integrate code from Stack user DannYo's comment here into my project. However, when I run my version of the code, I keep encountering errors with the "beforesend" functions not working properly. HTML <form action="" m ...

Avoid the automatic scrolling of a datatable to the top when clicking on a button within a column using jQuery

Is there a method to stop the datatable from automatically scrolling to the top when any of the buttons is clicked? ...

Leverage node rework CSS directly within your browser for seamless website

Looking to utilize the reworkcss/css library in the browser. Downloaded version 2.0.0 from GitHub and installed necessary packages with npm install. Attempted using requireJS, which supports processing the CommonJS Module Format by requiring index.js, bu ...

Is there a PHP function that functions similarly to JavaScript's "array.every()" method?

As I work on migrating JavaScript code to PHP, I am facing the challenge of finding a replacement for the array.every() function in PHP. I have come across the each() function in PHP, but it doesn't quite meet my requirements. ...

Using jQuery to switch between displaying full text and truncated text

How can I toggle the hidden text that appears after using the .slice function to remove the first 100 characters? This is the code snippet I am currently working with: .html <div class="col-sm-12"> <p class="pdp-product-description">Th ...

Using Express in Node.js to send a GET request to a different server from a Node route

When a client triggers a GET request by clicking a button on the index page, it sends data to a route that is configured like this: app.js var route = require('./routes/index'); var button = require('./routes/button'); app.use('/ ...

What is the best way to pass a variable value from a JavaScript function to a Python function within a Django framework

My goal is to use HTML and JavaScript to scan a QR code in nurse_home.html. I have successfully scanned and viewed the content of the QR code on the website, but I am facing an issue with POSTing the QR code output represented by <output type='POST ...

The GraphQL Resolver function that returns an object

When querying with GraphQL, I receive results in the following format: { "data": { "events": [ { "_id": "65f0653eb454c315ad62b416", "name": "Event name", " ...

Receive various JSON replies from PHP

I am currently developing an app using PhoneGap which involves a script to read a ticket code. The script performs two queries: one to update the ticket status in the database if it exists, and another to write a log in a separate table. This functionality ...

disabling empty elements in a React JS JavaScript component

Currently, I am retrieving data from an API where users can post content up to 3 times. However, if a user has not posted three times, empty boxes with padding and background color will appear. I want to remove all elements that do not have any content wit ...

Angular ng-show does not seem to evaluate properly

After receiving the JSON array object below: "Tools": [ { "name": "Submit a Claim", "position": 1, "isOn": true, "alert": null }, { "name": "My Recurring Claims", "position": 2, "isOn": true, "alert": null }, { "name": "Online Enrollment ...

What is causing the issue of the page overflowing in both the x and y axis while also failing to center vertically?

I've been trying to align the <H4> styled component to the center of the page using flex-box, but it's not working as expected. I also attempted using margin:0 auto, but that only aligned the H4 horizontally. Additionally, I'm investi ...

Encapsulation of JSON data with variable declaration

After generating a json data using the PHP code below: $index = array(); foreach($rows as $row) { $row['data'] []= (object) []; $index[$row['cat_id']] = $row; } // build the tree foreach($index as $id => &$row) ...

Is it possible to extract information from a form's POST request without relying on the traditional "action" attribute within form elements?

Last night, I was experimenting with ExpressJS and discovered something interesting when working with a simple code snippet: app.post('/contact', function(req, res, next) { res.send('Congratulations! You have submitted the form'); }) ...

Tap on a picture to increase the tally and save it to the server for all users to view the total number of likes

As someone without much background in backend development, I find myself facing a challenging question. Please bear with me if my technical terminology is not quite there. Essentially, I have a collection of images that I want users to be able to "like," ...

Retrieving date from timestamp in a node.js environment

Can someone help me figure out how to display my timestamp as the date in the front end? I've tried multiple methods without success. Here is the code snippet: formulaire.addEventListener('submit', posteValidation); /** * Function to add a ...

What is the reason for the E2089 Invalid typecast error when attempting to cast an open array parameter to an array type

I am currently using Delphi 2007 (Pre generics) and I have created several functions that can be used for all arrays of descendants of TObject. For example: function IndexOf(AArray : array of TObject; AItem : TObject) : integer; begin //... end; To han ...