Creating an HTML table from JSON data using JavaScript

I recently wrote some code that reads the contents of an XML file and converts it into JSON. The JSON data is then displayed in an HTML table. Everything seems to be working fine, but there's one issue - the first row of the table always shows as "undefined" in each cell. I've checked the code multiple times but can't seem to find the root cause. If anyone has any fresh ideas on how to solve this problem, please let me know!

<html>
<head>
<h1><u>USA State Information</u></h1>
</head>
<body>
<p><b>Please select an area of the USA from the dropdown list below.</b></p>
<p><select name="area" onchange="findXML(this.value)">

<?php
//set directory and open it
$xmldir = 'XML';
$dir = opendir($xmldir);

//create array and read through files in directory
$xmlfiles = array();
while ($file = readdir($dir))
{
    //if the first char is not '.' then add to array
    if (substr($file,-1,1) !== ".")
    {
        $xmlfiles[] = $file;
    }
    else
    {
        //do nothing
    }
}

echo '<option value="select">Select</option>';

foreach($xmlfiles as $area){ 
    echo '<option value="'.$area.'">'.$area.'</option>'; 
}
echo '</select>';

//close directory
closedir($dir);
?>
</p>
<p>
<div id=tbl>
</div>
<table id="elems" border="1" cellspacing="1" cellpadding="5">
<tr>
<td><b>Name</></td>
<td><b>Number</></td>
<td><b>Joined</></td>
<td><b>Population</></td>
</tr>
</table>
<script>
function findXML($area) {
$area = "XML/" + $area;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET",$area,true);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
//find number of elements in the XML file
$length = xmlDoc.getElementsByTagName("name").length;

var JSONObject = [{}];
for (i=0; i!=$length; i++){
    //do something

    JSONObject.push(
    { "name":(xmlDoc.getElementsByTagName("name")[i].childNodes[0].nodeValue),
    "number":(xmlDoc.getElementsByTagName("number")[i].childNodes[0].nodeValue), 
    "joined":(xmlDoc.getElementsByTagName("joined")[i].childNodes[0].nodeValue),
    "population":(xmlDoc.getElementsByTagName("population")[i].childNodes[0].nodeValue) }
    );
}

r=1;
i=0;
for (i=0; i!=($length); i++){

    var tblr = document.getElementById("elems").insertRow(r);
    var cell1= tblr.insertCell(0);
    var cell2= tblr.insertCell(1);
    var cell3= tblr.insertCell(2);
    var cell4= tblr.insertCell(3);
    cell1.innerHTML = JSONObject[i].name;
    cell2.innerHTML = JSONObject[i].number;
    cell3.innerHTML = JSONObject[i].joined;
    cell4.innerHTML = JSONObject[i].population;
    r++;
}

}
</script>
</p>

</table>
</body>
</html>

Answer №1

Upon further investigation, it appears that I have identified the root of the problem:

var JSONObject = [{}];

should actually read as follows:

var JSONObject = [];

The reason for this correction is that by initializing the array with an empty object at the first index, you are causing issues when iterating through the JSONObject array. Since the empty object does not contain the properties name, number, etc., attempting to access them will result in undefined values being returned.

Answer №2

Do you have any experience with:

for (i=1; i!=($length); i++){

Maybe your index begins at 1 instead of 0

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

404 error occurs when AngularJS removes hash symbol from URLs

I successfully eliminated the hash from my Angular JS website using the following code snippet: $locationProvider.html5Mode(true); Now, the previously displayed URL has been replaced with . The issue I'm facing is that when I do a hard refresh (Ct ...

Updates to class variable values in jQuery are failing to take effect

Attempting to create my first JavaScript class has presented some challenges, specifically when it comes to updating a class variable. Despite hours of testing different approaches, I still can't seem to get it right! function ClassName(productId) { ...

Attempting to modify PHP query following submission of data via Axios in Vue application

Fetching a JSON object through a PHP query from a service known as BullHorn can be done like this: <?php echo getBhQuery('search','JobOrder','isOpen:true','id,title,categories,dateAdded,externalCategoryID,employmentTy ...

AngularJS personalized date selector directive

Looking to create a unique datepicker directive with a personalized template. Feeling lost on where to begin constructing it... Any suggestions on incorporating date data into my directive? Your guidance or tips on how to approach this project more effe ...

Add to MongoDB only if the entry does not already exist; otherwise, move on

Can I perform a conditional insert in MongoDB? //Pseudo code Bulk Insert Item : If Key exists Skip, don't throw error If key does not exist Add item If I do single inserts, it might return an error or insert into the collection. But is thi ...

The npm script for running Protractor is encountering an error

Currently, I am facing an issue while trying to execute the conf.js file using an npm script. The conf.js file is generated within the JSFilesRepo/config folder after running the tsc command as I am utilizing TypeScript in conjunction with protractor-jasmi ...

Customize the CSS for material-ui buttons or create a new style altogether

Looking to customize the background color of a material UI RaisedButton, I have encountered a challenge. This is what I currently have: const style = { backgroundColor: 'green' }; export default class CreateLinksave extends React.Component { ...

The magic of jQuery when chaining AJAX callback functions

I have a centralized ajaxSuccess callback function that needs to initialize components from various AJAX calls across the project. Here is an example: $(document).ajaxSuccess(function (response, status, xhr) { initComponents(); }); For module-level a ...

Tips for storing the output of a script URL in a JavaScript variable

I am currently facing an issue with running a script in the 'head' element of a webpage. The script makes an API call to a specific URL and retrieves results in the form of a JavaScript array. However, I am encountering difficulty because the API ...

Adjust the font size to fit within the container

My webpage features a bootstrap 4 container with three columns that adjust on screen sizes above the md breakpoint (col-md-4). Each column contains an img with the class img-fluid, and when hovered over, text description appears. I want this hover text to ...

Implementing mouse event listeners on dynamically created elements in Vue.js

I've been curious if anyone has attempted something similar to the following code snippet (created within a Vue.js method): for (let i = 0; i < this.items.length; i++) { let bar = document.createElement('div'); bar.className = this ...

Sending the handleSubmit() function to the child component does not alter the state of the parent component

I just started learning React and Javascript. Currently, I am working on a form where users can specify the details of a "Mob". Upon submitting the form, I anticipate that handleSubmit() (which is passed down from the parent component) will update the sta ...

An AngularJS Dilemma: Troubleshooting JSON Integration

I am working with a JSON source and trying to fetch results from it using a post request. Interestingly, when I use the POSTMAN extension in Chrome, everything works perfectly fine. However, when I try the same thing with AngularJS, the page keeps loading ...

Issue: Spaces are not being displayed between items in the @Html.DisplayFor statement within the Foreach

I have encountered a few similar queries on this platform and attempted the suggested solutions, but unfortunately, they did not resolve my specific issue. Within my view, I am using @Html.DisplayFor in a Foreach loop to display all GroupIDs in a particul ...

The sorting function in Vue.js, _.orderBy, seems to be having trouble sorting

UPDATE This is the json data retrieved through an API using axios. bannerData= [ { "id": 118, "title": "Geruchsbel\u00e4stigung", "location": "DOR", "pressInformation": [ { ...

What methods can I utilize to showcase the JSON data on my webpage efficiently?

I'm currently working on a script that makes an ajax request. The Cloud appears to be responding with JSON data, but I'm not sure how to display this data on my webpage. Any suggestions? Here you can find a link to view the neatly formatted JSON ...

Tips on how to dynamically uncheck and check the Nebular checkbox post-rendering

I incorporated a nebular theme checkbox into my Angular 8 App. <nb-checkbox [checked]="enable_checked" (checkedChange)="enable($event)">Enable</nb-checkbox> I am able to update the checkbox using the Boolean variable "enable_checked". Initia ...

The parameter 'data' is assumed to have an 'any' type in React hooks, according to ts(7006)

It's perplexing to me how the 7006 error underlines "data," while in the test environment on the main page of React Hooks (https://react-hook-form.com/get-started#Quickstart), everything works perfectly. I'm wondering if I need to include anothe ...

Assistance from Meteor for storing Cached Cursors

I have a Template that features a select element allowing users to filter through a collection of Objects displayed on a table. The result of the select is stored in a ReactiveVar, which is then utilized in querying a Helper to retrieve the Objects for the ...

extracting ng-repeat values and passing them to the controller

I have created a form that dynamically increases whenever the user clicks on the add sale button Here is the HTML code: <fieldset data-ng-repeat="choice in choices"> <div class="form-group"> <label for="name"> Qu ...