The table is unable to properly display the array data

My code includes an AJAX function that sends a GET request to an API and receives data in the format shown below:

{
    "firstname": "John",
    "lastname": "Doe",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6d090208072d0a000c040041170e0200">[email protected]</a>",
    "subjects": [
      {
        "id": 1,
        "name": "maths"
      },
      {
        "id": 2,
        "name": "chemistry"
      }
    ]
  }

I'm trying to display this data in a table but I'm struggling with formatting the 'subjects' array correctly, specifically as a list within one cell of the table. I attempted to place the array data into a nested table within the main table, however, it's not rendering properly. It seems like there is an issue with my iteration loops.

function getPeople() {


     $.ajax({
         type: "GET",
         url: "http://example.com",
         contentType: "application/json; charset=utf-8",
         crossDomain: true,
         dataType: "json",
         success: function (data, status, jqXHR) {



             // Populating a table with the JSON
           $("table.mytable").html("<tr><th></th><th>First Name</th><th>Last Name</th><th>Subjects</th></tr>"  );

for (var i = 0; i < data.length; i++) {

        for (var j = 0; j < data[i].subjects.length; j++) {

          var subjects = data[i].subjects[j];
        $("table.insidetable").append('<tr><td>' + subjects + 'tr><td>')
      }

    $("table.mytable").append('<tr><td><input type = "checkbox" id = '+data[i].id+'>'  + "</td><td>" + data[i].firstname + "</td><td>" + data[i].lastname + "</td><td>" + "table.insidetable"  + "</td></tr>");
}

         },

         error: function (jqXHR, status) {
             // Error handler
             console.log(jqXHR);
             alert('fail' + status.code);
         }
      });
   }

Answer №1

Here is the functional (tested) script.

var info = [{
  "firstname": "John",
  "lastname": "Doe",
  "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f1959e949bb1969c90989ddf929e9c">[email protected]</a>",
  "subjects": [
    {
        "id": 1,
    "name": "maths"
    },
    {
        "id": 2,
    "name": "chemistry"
    }
        ]
},
{
  "firstname": "Steve",
  "lastname": "Gentile",
  "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="651611001300250208040c094b060a08">[email protected]</a>",
  "subjects": [
    {
    "id": 1,
    "name": "history"
    },
    {
        "id": 2,
    "name": "geography"
    }
  ]
}];

$("table.mytable").html("<tr><th></th><th>First Name</th><th>Last Name</th><th>Subjects</th></tr>");

for (var i = 0; i < info.length; i++) {
    var subjectList = '';

    for (var j = 0; j < info[i].subjects.length; j++) {
      subjectList += '<li>' + info[i].subjects[j].name + '</li>';
    }

    $("table.mytable").append('<tr><td><input type="checkbox" id=' + i +'/></td><td>' + info[i].firstname + '</td><td>' + info[i].lastname + '</td><td><ul>' + subjectList  + '</ul></td></tr>');
}

It looks like there are multiple issues in the following code block, such as:

  • Tags not being properly closed
  • Usage of properties that do not exist (info[i].id)
  • Mismatching single and double quotes
...
$("table.mytable").append('<tr><td><input type = "checkbox" id='+info[i].id+'>'  + "</td><td>" +info[i].firstname + "</td><td>" + info[i].lastname + "</td><td>" + "table.insidetable"+ "</td></tr>");

Answer №2

Could it be possible that a '<' is missing from your code?

Take a look at this line:

 $("table.insidetable").append('<tr><td>' + subjects + 'tr><td>')

Furthermore,

$("table.mytable").append('<tr><td><input type = "checkbox" id = '+data[i].id+'>'  + "</td><td>" + data[i].firstname + "</td><td>" + data[i].lastname + "</td><td>" + "table.insidetable"  + "</td></tr>");

It seems incorrect to append the string "table.insidetable" in your code. It will display as plain text "table.insidetable" instead of the table content. You might want to consider using something like $("table.insidetable").val()

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 there a way to transfer table row data to another table by simply clicking on the corresponding checkbox in the same row?

I'm working with a table that includes 4 fields: service, amount, tax, and action. My challenge is to have the data from any row in the first table added to a second table when its checkbox is selected. The second table should have the same fields a ...

How to Use Google Calendar API to Retrieve Available Time Slots for a Given Day

Is there a way to extract the list of available time slots from my Google Calendar? Currently, I am only able to retrieve the list of scheduled events. I am utilizing the Google Calendar npm package. google_calendar.events.list(calObj.name,{ timeMin ...

Achieving priority for style.php over style.css

Having trouble with theme options overriding default CSS settings in style.css. Here's what I have in my header.php: <link rel='stylesheet' type='text/css' media='all' href="<?php bloginfo( 'stylesheet_url&apo ...

What is the process for importing an md file in a create-react-app project using JavaScript?

Attempting to execute the blog example provided on Material UI's getting started page. However, encountering an issue with the source code: Inside blog.js import post1 from './blog-post.1.md'; . . . return( <Main>{post1}<Main/> ...

The timer is malfunctioning

I am new to JavaScript and looking to create a simple countdown. I came across this script: http://codepen.io/scottobrien/pen/Fvawk However, when I try to customize it with my own settings, nothing seems to happen. Thank you for any assistance! Below is ...

Utilizing the fs module in Node.js

Hello friends! Currently I am faced with an issue while trying to import the fs module in nodejs. Initially, I utilized require to import it like so: const fs = require('fs'); Everything was functioning smoothly until recently when it suddenly ...

What is the proper way to provide parameters in a GET request using Axios?

Recently, I have been attempting to include the api_key in the get request parameter using axios Below is the snippet of my code: const instance = axios.create({ baseURL: "https://api.themoviedb.org/3" }); export function crudify(path) { function get ...

Tips on showcasing the elements within a div container using flexbox

Seeking advice on positioning items/cards using flexbox in my initial react app. The issue lies with the div within my card component where applying display: flex; turns every card into a block (column-like) structure, flexing only the content within each ...

Encountering an Error when Integrating Pusher (real-time data library) with Next.js: PusherRequestError - Unexpected status code 400

I encountered an issue while trying to integrate Pusher into my Next.js application due to Vercel's restriction on websockets in their serverless functions. The error message I keep receiving after running the program with Pusher is: error - unhandled ...

What could be the reason for my post jQuery Ajax request sending JSON data?

After downloading some code, I came across the following fragment: function FetchCommentsBySessionIDWCF_JSON() { varType = "POST"; varUrl = "service/CommentSessionIDWCFService.svc/FetchCommentsByPost"; varData = ' ...

What is preventing me from displaying the results on the webpage?

Currently, I am utilizing Express alongside SQLite and SQLite3 modules. However, upon running the server, the data fails to display on the initial request. It is only after a page refresh that the data finally appears. I attempted a potential solution by ...

Place the border image underneath the div element

I successfully added a border image to the right side of my div, but now I want it to extend slightly below the div. Is there a way to increase the height of the border image? Or should I just float the image next to the div and how would I go about doing ...

What is the best way to exchange configuration data among Javascript, Python, and CSS within my Django application?

How can I efficiently configure Javascript, Django templates, Python code, and CSS that all rely on the same data? For example, let's say I have a browser-side entry widget written in Javascript that interacts with an embedded Java app. Once the user ...

What is the best way to delete a property from an object in an array using Mongoose? This is crucial!

Doc - const array = [ { user: new ObjectId("627913922ae9a8cb7a368326"), name: 'Name1', balance: 0, _id: new ObjectId("627913a92ae9a8cb7a36832e") }, { user: new ObjectId("6278b20657cadb3b9a62a50e"), name: 'Name ...

What makes the nav class different from the navbar class in Bootstrap?

Recently, I delved into learning about bootstrap and web development. To my surprise, I stumbled upon the nav and navbar classes in bootstrap 4. I'm curious to know what sets them apart from each other and when it's best to use one over the other ...

Click to start viewing the video

I'm attempting to have a video play when clicked, either on the video itself or around the video. There are multiple videos on the page and I've tried various solutions including the script below which didn't work. $('video'). ...

Navigating Vue 3's slot attributes: A step-by-step guide

Currently, I am facing an issue with a Vue component named MediaVisual. This component contains a slot. The problem arises when attempting to retrieve the src attribute of the slot element that is passed in. Surprisingly, this.$slots.default shows up as u ...

Strange symbols were stored in the database after saving the textarea value

After submitting a form, text entered into a text area is being saved to my database. However, in one instance, certain characters such as • are appearing in the field. For example: • Text When retrieving the data from the database using Jav ...

Place a Three.js scene within a jQuery modal dialogue box

I am attempting to integrate a Three.js scene into a jQuery modal window. The objective is to utilize the Three.js scene in a larger window size. This scene should be displayed after clicking on an image that represents the scene in a smaller dimension. Y ...

JavaScript - continuously update the image marked as "active"

I have a collection of 4 pictures that I want to rotate through in my web application. Each picture should have the "active" class applied to it, similar to when you hover over an image. .active, .pic:hover{ position: absolute; border: 1px solid ...