"Displaying Undefined Content when an Incorrect Value is Added, but functioning correctly with the right

I am attempting to populate the HTML table below with data from a JSON file:

When I set var i = "0";, I receive undefined, but changing it to var i = "dv"; results in nothing being displayed.

I am uncertain of the error I am making and what is causing this problem. I suspect it might be related to this line

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

Here is the code and the JSON file: https://pastebin.com/embed_js/rhUz1U5r

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script>
<script>

var currentTime = new Date()
var month = currentTime.getMonth()
var day = currentTime.getDate()
var dv = ('0' + '/' + month + '/' + day)

    $(function() {
        $.getJSON('spellData.json', function(data) {
            var content;
            for (var i = "dv"; i < data.length; i++) {

                content = $('<tr/>');

                    content.append("<table>");

                    content.append("<tr> <th> Prayer </th> <th> Start </th> <th> Jamaat </th> </tr>");

                    content.append("<tr> <td> Salat Al-Fajr: </td> <td> " + data.fajr_begins + " </td> <td> " + data.fajr_jamah + " </td> </tr> ");

                    content.append("<tr> <td> Sunrise: </td> <td> " + data.sunrise + " </td> <td> " + data.sunrise + " </td> </tr> ");

                    content.append("<tr> <td> Salat Al-Ishraq: </td> <td> " + data.ishraq + " </td> <td> " + data.ishraq + " </td> </tr> ");

                    content.append("<tr> <td> Salat Al-Zuhur: </td> <td> " + data.zuhr_begins + " </td> <td> " + data.zuhr_jamah + " </td> </tr> ");

                    content.append("<tr> <td> Salat Al-Asr: </td> <td> " + data.asr_mithl + " </td>  <td> " + data.asr_jamah + " </td>  </tr> ");

                    content.append("<tr> <td> Salat Al-Magrib </td> <td> " + data.maghrib_begins + "</td> <td> " + data.maghrib_jamah + " </td> </tr> ");

                    content.append("<tr> <td> Salat Al-Isha </td> <td> " + data.isha_begins + " </td>  <td> " + data.isha_jamah + " </td> </tr> ");

                    content.append("</table>");

                $('table').append(content);
            }
        });
    });
</script>
</head>
<body>
    <div id="djpyer"> </div>
    <table></table>
</body>

Answer №1

In order to proceed, you must first obtain a valid JSON file, then you can convert it into a JavaScript object for manipulation. Within your data, there are two keys, 11 and 12, and it seems that you only require the value of 11 to construct the table.

The data that needs to be manipulated is located within an array. To work with arrays, you can utilize built-in methods from the Array class. For instance, I have used Filter, with Boolean as a callback function (not a constructor), to eliminate any null values from the array. Additionally, I have employed forEach to iterate over each element of the array.

Based on your code, I have attempted to understand your objective and have implemented the following solution. It is essential to note that the snippet utilizes a variable to store the stringified JSON. You can substitute it with $.JSON along with a callback function to fetch data from your file.

const table = $('#content')

$(function() {
  const data = JSON.parse(json_string)["11"].filter(Boolean);
  
  data.forEach(function(el) {

    // Code Snippet to manipulate and append table rows here

  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>

<table>
  <thead>
    <tr>
      <th> Prayer </th>
      <th> Start </th>
      <th> Jamaat </th>
    </tr>
  </thead>
  <tbody id="content"></tbody>
</table>

<script>
  const json_string = 'Insert your JSON data here'
</script>

Answer №2

For the loop to function correctly, make sure to initialize your variable dv with a value of 0. Additionally, avoid adding any content outside of the closing tag.

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 the reason for my ajax request coming back with no data?

When I make this ajax request: $.ajax({ type: "POST", url: "/admin/RoutingIndicators/Add", data: { newSecondaryRI: newRi }, success: function () { alert('hit'); document.location.reload(true); }, error: fu ...

JS is programmed to automatically redirect the user after they have clicked on a div element and a

I'm having trouble with this code that is supposed to redirect a user after they click on the div and then the next button. It's not working for me :( Here is the code I am using: $("a.xxx").click(function() { $(this).toggleClass("yyy"). ...

Is there a way to make this AngularJS service wait until it has a value before returning it?

Multiple controllers call a service that loads data into an object named categories: .service('DataService', ['$http', '$q', function($http, $q) { var categories = {}; // Public API. return({ setCategory ...

Execute a function and simultaneously input data into MySQL using Node JS

Is there a way to simultaneously insert data from multiple external data sources into a database? I have several APIs/Endpoints that provide the same dataset, and I want to insert them all at once. For instance: Right now, my code loops through each API ...

What is preventing me from reading the input value in AngularJS using jQuery?

Just starting out with angularjs and I need help with this code sample: <ng-input theme='fumi' id='txtEmail' label='Email Address' icon='icon icon--fumi mdi mdi-select-all' style="font-size:medium;width:40%;"&g ...

Terminating a function during execution in JavaScript/TypeScript

Currently, I am in the process of developing a VSCODE extension using TypeScript. Within this extension, there is a particularly large function that is frequently called, but only the final call holds significance. As a solution, I am attempting to elimina ...

Obtain data from JSON ARRAY in BigQuery

My goal is to extract data from a JSON array using the query found here: with `project.dataset.table` as ( select '{"fruit":[{"apples":"5","oranges":"10","pear":"20"}, ...

Error message: "Angular.js encountered a typeError stating that V2.example is not a function"

Having recently started learning Angular.js, I came across a tutorial that was created about a year ago. In this tutorial, I am attempting to implement a search feature that takes user input and searches for it on Github.com. Below is the HTML code snippet ...

What is the best way to calculate the number of days that have passed since a certain

Hey there, I've got this 10 Dec, 2019T14:07:21 date format from the backend. My goal is to determine how many days ago it was. For example, today is the 20th, so if the date is today's date, it should show as 0 days ago. ...

Interested in halting the code execution once a match is found?

In Angular JS, I have developed a service method that checks whether any of the potential statuses in an array (pendingApplications) match any of the set statuses in another array (applicableStatuses). In order for this to function correctly, the method ...

Guide to utilizing an if statement to return a string as the title in a Tooltip pro

When attempting to dynamically set the title of a tooltip based on a function and using an if statement, I encountered an error. const getStatusMessage = (answer: AnswerStatus) => { if (answer == AnswerStatus.ANSWER_SUBMITTED || answer == AnswerStatus ...

Tips for keeping a floating action button visible at the bottom of the screen at all times

I am currently utilizing the Material UI framework. I have a floating action button that I would like to display in a specific position on the page without it moving when scrolling, and I am also wondering if this is a common issue. Below is the code sn ...

There seems to be an issue with the audioElement.src, which I used to run and play different songs. However, it is now displaying a 404

Array.from(document.getElementsByClassName('songItemPlay')).forEach(function (item) { item.addEventListener('click', (evt) => { playAllSongs(); position = parseInt(evt.target.id); evt.target.classList.re ...

Trimming whitespace from strings within HTML tag attributes can be achieved using various methods

I have been reviewing the .cshtml pages of a website with the aim of adding ID attributes to various divisions and elements for testing purposes. These pages utilize AngularJS, and many of the elements I need to add ID attributes to are part of a list tha ...

Decoding JSON data in Flutter - _InternalLinkedHashMap<String, dynamic>

Struggling to parse JSON in my flutter project, I've attempted the code below. Here's an example of the JSON data: { "statusCode": 200, "message": "", "result": [ { ...

Sending a variable to a function in JavaScript (winJs) from a different function

Greetings! Currently, I am developing a Windows 8 app using Java Script. function fetchFromLiveProvider(currentList, globalList,value) { feedburnerUrl = currentList.url, feedUrl = "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&outpu ...

Scrolling using JavaScript's 'smooth scrolling' feature is currently disabled

Background of the Issue: I am in the process of creating a one-page website using Twitter Bootstrap 3 within an ASP.NET MVC project. The Challenge: My current challenge involves implementing 'smooth scrolling' functionality that scrolls to the ...

Tips for showing images with the full path URL retrieved from JSON using AngularJS

I am currently working on a project that involves displaying images from a JSON file. The URLs of these images are stored in the JSON file. Currently, my code is only outputting the URLs themselves, which is expected. However, I am looking for a way to act ...

Using AngularJS in an ASP.NET MVC application to load partial views

In the process of developing an ASP.net MVC application. Currently, I am incorporating a partial view within a div using a combination of jQuery and AngularJS: By performing an AJAX call through AngularJS and assigning the returned data as the content wi ...

When attempting to execute the "npm run start" command in a ReactJS environment, an error message appeared

'react-scripts' command is not being recognized as a valid internal or external command, able to use program or batch file. npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! [email protected] start: react-scripts start npm ERR! Ex ...