Show data from an API in an HTML table

I encountered an issue with an API, and despite trying

console.log(response.[""0""].body
) to view the response in the console, it does not seem to be working. My goal is to extract all the data from the API and display it in a table.

Below is my code:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
    // JavaScript Code
    
    var root = 'https://jsonplaceholder.typicode.com';
    $.ajax({
        url: root + '/posts',
        method: 'GET',
        success: function(response) {
            console.log(response);
        }
    });

    var body = document.getElementsByTagName('body')[0];
    var table = document.createElement('table');
    body.appendChild(table);
    table.setAttribute('id', 'mytable');

    var createRow = function(cell1, cell2) {
        var row = document.createElement('tr');
        row.appendChild(cell1);
        row.setAttribute('class', 'row');
        row.appendChild(cell2); 

        return row;
    }

    var createCell = function(value) {
        var cell = document.createElement('td');
        cell.setAttribute('class', 'cell');
        cell.innerText = value;
        return cell;
    }

    table.appendChild(createRow(createCell('Mihaela'), createCell('11')))
</script>

Answer №1

To demonstrate the power of the new Fetch API, I have created a sample using vanilla JavaScript without any external dependencies.

const root = 'https://jsonplaceholder.typicode.com';

const asyncFetchPosts = async() => (
  fetch(`${root}/posts`)
  .then(res => res.json())
);


const start = async() => {
  const posts = await asyncFetchPosts();
  const tableHead = document.getElementById('myTableHead');
  const tableBody = document.getElementById('myTableBody');
  
  // Extract all property keys from the first post
  // Array: [userId, id,title,body]
  const keys = Object.keys(posts[0]);

  // Add table header row
  const tableHeadRow = tableHead.insertRow(tableHead.rows.length);

  // Iterate over keys to generate the header
  keys.forEach((key, i) => {    
    const newCell = tableHeadRow.insertCell(i);
    const newText = document.createTextNode(key);
    newCell.appendChild(newText);
  });
  
  // Loop through all posts
  posts.forEach(post => {
    const newRow = tableBody.insertRow(tableBody.rows.length);
    
    // Now loop through the keys for each post
    keys.forEach((key, i) => {
      const newCell = newRow.insertCell(i);
      const newText = document.createTextNode(post[key]);
      newCell.appendChild(newText);
    })
  });
}

// Call the start function
start();
<table id="myTable" border="1">
  <thead id="myTableHead">
  </thead>
  <tbody id="myTableBody">
  </tbody>
</table>

Answer №2

One troubleshooting tip is to utilize console.log(response[0].body)

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 could be causing the lack of value appearing after I clicked the button?

Setting the value for the array of images as an empty string does not return the expected result. When I move one of the 4 images and click the button, I anticipate a new array with the information of one of the four images including src, x, and y coordina ...

Is the error message "not a function" appearing when calling a function from a parent to a child?

I am trying to understand parent-child relations in React as I am new to it. In my understanding, the following scenario should work: I have a parent component called <Home/> and within it, there is a child component called <ProjectDialog>, wh ...

Is there any issue that you can spot with this js / jQuery code?

Presented below is a script that prompts the user to confirm clicking a button based on a system setting. The system setting is saved in a hidden field established from the code-behind. Markup: <asp:HiddenField ID="hfConfirmOnApproval" runat="server" ...

Javascript Promise: managing the flow of execution

There are a series of tasks that I need to accomplish using an API. It's crucial that these functions are executed sequentially. Each of the functions mentioned below returns a valid promise. a(analyticsConfig._listConfig) .then(function() { ...

The combination of Nest, Fastify, Fastify-next, and TypeOrm is unable to locate the next() function

In my attempt to set up Nest with Fastify and Next using the fastify-next plugin, everything went smoothly until I added TypeOrm for MongoDB integration. Upon loading the AppModule, Nest throws an error indicating that the .next() function cannot be found ...

What methods can a Discord Bot use to respond with specific messages to individual users?

Hey there! I'm dipping my toes into the world of coding and thought it would be fun to create a Discord bot that gives different responses each time it's mentioned. Just so you know, I'm working with Discord.js version 13 for this project. ...

Showing ng-attributes in haml partials in Rails using jQuery ajax and $q

As I work on developing an Angular Frontend for an existing Rails Application, I have come across the challenge of integrating $q in my current setup. While I understand that transitioning to a REST API served directly to ngResource would be ideal, the com ...

Updating the handler function for AutoComplete with Checkbox in Material UI using React JS

I am looking to include an <AutoComplete /> field in my form. The options for this field are fetched through a get request, and here is the result displayed in the console. [ { "uid": "c34bb0ed-9f63-4803-8639-a42c7e2a8fb0&q ...

Transfer an Array of Objects containing images to a POST API using Angular

Looking to send an array of objects (including images) to a POST API using Angular and Express on the backend. Here's the array of objects I have: [{uid: "", image: File, description: "store", price: "800"} {uid: "f ...

Develop a custom dropdown menu using JavaScript

I've been working on creating a dropdown menu that appears after selecting an option from another dropdown menu. Here's the HTML code I'm using: <br> <select id ="select-container" onchange="addSelect('select-container') ...

What is the best way to incorporate an AJAX GET request into an HTML element?

Currently, I am attempting to execute a JavaScript code that will convert all <a></a> elements found within another element <b></b> (the specific name in the HTML) into links that trigger an HTTP get request. However, the code I hav ...

Exploring Nested Data in MongoDB Aggregation using $match and $project

Struggling with crafting a Mongoose Aggregate Query to extract the permissions object of a specific member within a deeply nested structure of business data. MongoDB's documentation on this topic is lacking, making it hard for me to progress. Sample ...

Tips for improving the performance of the JavaScript code mentioned

Can you assist with optimizing the code below? The question at hand is whether all values in this array need to be checked to see if two of them sum up to 8. If yes, then we should identify the indexes of these values. const arr = [1, 2, 3, 4, 5]; const ...

Is there a way to access the rear camera on a mobile device using webcam.js?

Currently, I am utilizing webcam.js from the following link: https://github.com/jhuckaby/webcamjs. When accessing the website on mobile devices, the front camera tends to open by default. My objective is to switch this default setting to access the rear ...

Firebase Firestore replicates documents, subcollections, and data

Here is a sample structure: .doc Name .colection 1 .doc sub_doc .collection sub_col1 .doc sub_doc .collection 2 .doc sub_doc I want to duplicate this document, including all its sub-collections, to create an ex ...

Assign a value to the cookie based on the input from the form

I recently asked a similar question, but it seems like I missed providing some context, which is why I couldn't get it to work. My goal is to set a cookie value of a form entry when clicking on it (using the carhartl jquery plugin), but nothing happen ...

Is there a way to use flexbox in a grid to center only a specific tab from MUI?

I am working with an array of tabs and encountering a layout issue. The tabs need to share the available space when there's more than one tab, but when there's only one tab, it should be positioned in the middle of the column. How can I address t ...

Vuejs Error: The 'in' operator cannot be used for searching

I am facing an issue with my form and VueJS. Upon clicking the "Login" button, I intend to change the text on the button. However, instead of achieving this, I encounter an error stating 'cannot use 'in''. Below is the HTML code snippet ...

Leveraging JSON Data in Highcharts

I am looking to create a column range chart using Highcharts to display a series of high and low temperatures. I found a demo example that showcases the kind of chart I want on the Highcharts website at: http://www.highcharts.com/stock/demo/columnrange Th ...

I have my doubts about whether I am implementing the recapcha API correctly in a React application

I implemented the recapcha API in order to prevent bots from submitting posts on a forum site. As a new developer, I'm not sure if this is a real threat or not, as the users are limited to a maximum of 3 posts before they have to pay for more. I' ...