Retrieving information from a JSON file and displaying it in an HTML table through an asynchronous

I need to retrieve data from a server and display it in an HTML table. The server contains an array of weather forecast information as shown below.

[{"date":"19\/08\/2020","weather":"Sunny","temperature":30,"temp_unit":"celcius"}, 
{"date":"30\/08\/2020","weather":"Sunny","temperature":31,"temp_unit":"celcius"}, 
{"date":"21\/08\/2020","weather":"Cloudy","temperature":29,"temp_unit":"celcius"}, 
{"date":"22\/08\/2020","weather":"Sunny","temperature":29,"temp_unit":"celcius"}, 
{"date":"23\/08\/2020","weather":"Sunny","temperature":31,"temp_unit":"celcius"}, 
{"date":"24\/08\/2020","weather":"Sunny","temperature":30,"temp_unit":"celcius"}, 
{"date":"25\/08\/2020","weather":"Cloudy","temperature":28,"temp_unit":"celcius"}, 
{"date":"26\/08\/2020","weather":"Cloudy","temperature":27,"temp_unit":"celcius"}, 
{"date":"27\/08\/2020","weather":"Sunny","temperature":29,"temp_unit":"celcius"}, 
{"date":"28\/08\/2020","weather":"Sunny","temperature":28,"temp_unit":"celcius"}, 
{"date":"29\/08\/2020","weather":"Cloudy","temperature":28,"temp_unit":"celcius"}, 
{"date":"30\/08\/2020","weather":"Sunny","temperature":31,"temp_unit":"celcius"}]

I've created the following code to retrieve the data using an AJAX call, but when I try to display it in a table, all values show as undefined.

//include CSS in this file
import './style.css';

//jQuery already imported
import $ from 'jquery';
// AJAX call to load data

var myArray = []

$.ajax({
  method: 'GET',
  url: 'https://www.seetrustudio.com/data.php',
  success: function(response) {
    myArray = response
    buildTable(myArray)
    console.log(myArray)
  }
})

function buildTable(data) {
  var table = document.getElementById('myTable')

  for (var i = 0; i < data.length; i++) {
    var row = `<tr>
                            <td>${data[i].date}</td>
                            <td>${data[i].weather}</td>
                            <td>${data[i].temperature}</td>
                            <td>${data[i].temp_unit}</td>
                      </tr>`
    table.innerHTML += row
  }
}

How can I resolve this issue and correctly populate the HTML table with the list?

Answer №1

The issue here lies in the fact that the response is being returned as plain text, necessitating the use of JSON.parse to properly interpret the response.

$.ajax({
  method: 'GET',
  url: 'https://www.seetrustudio.com/data.php',
  success: function(response) {
    buildTable(JSON.parse(response));  <---- you must include this line.
  }
})

function buildTable(data) {
  var table = document.getElementById('myTable')

  for (var i = 0; i < data.length; i++) {
    var row = `<tr>
                            <td>${data[i].date}</td>
                            <td>${data[i].weather}</td>
                            <td>${data[i].temperature}</td>
                            <td>${data[i].temp_unit}</td>
                      </tr>`
    table.innerHTML += row
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id='myTable'></table>

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

Serve static assets files based on the route path instead of using absolute paths

Within Express, I have set up the following route: app.get('/story/:username', function(req, res){ res.render('dashboard.ejs'); }); Prior to that, I am serving any static files located in /public: app.use(express.static(__dirname ...

Utilizing previously written HTML code snippets

While working on a page within a legacy application, I find myself repeatedly reusing a large HTML block of code. The entire HTML and JavaScript codebase is quite old. The specific HTML block in question spans over 200 lines of code. My current strategy in ...

The ngModel directive automatically clears the checkbox's Checked status

Currently, my Angular code is set up to validate a checkbox using ng-model: <input type="checkbox" name="news1" value="news1" ng-model="news" <c:if test="${xxxx == yes'}">checked="checked"></c:if>> <label ng-click="news1();"&g ...

Dynamic and static slugs in Next.js routing: how to navigate efficiently

I am facing a scenario where the URL contains a dynamic slug at its base to fetch data. However, I now require a static slug after the dynamic one to indicate a different page while still being able to access the base dynamic slug for information. For Ins ...

What is the best way to include a new user in the memory database when there is no database or storage back-end?

During an online test, I was given the task of adding a user to a database stored in memory. The request body required JSON formatting as shown below: { "id": "aabbbccddeeefff", "name": "User One", "hobbies": [ "swim", "sing", "workout" ] } (Users ...

The submission of the form using AJAX is currently experiencing issues

My current issue involves ajax not functioning as intended. I have a form that is being submitted through ajax to my php file for the purpose of updating my database. The database update is successful, but there seems to be a problem with the ajax function ...

Automatically insert nested object keys and values from jQuery into their respective div elements

Below is a sample object that I am working with: "experience": { "1": { "jobtitle": "job_title", "companyname": "company_name", "companytown": "company_town", "companycountry": "company_country", "summary": "Sum ...

Blogger Extension - Cross Domain Communication

As I work on creating a blogger plugin, my goal is to send information from the blog page for analytic purposes and then display the results on the visitor's page. Initially, I tried sending the page content using an ajax call but encountered an error ...

Show a collection of files in a table format

Here is the current code I have: index.html <!DOCTYPE html> <html> ... </form> </div> </body> </html> And here is my code.gs function doGet() { return HtmlService.createHtmlOutputFromFile('index'); } ...

Enhance Laravel 5 by integrating browserify into the Elixir build process

My workflow for transforming coffee to js using browserify, browserify-shim, and coffeeify looks like this: I work with two main files: app.coffee and _app.coffee, designated for frontend and backend respectively. These files are located in resources/coff ...

Building a JSON-powered navigation bar with Bootstrap 4

Looking to create a custom navigation bar using Bootstrap 4 and populate it with items from a JSON file. Despite researching various methods, there seems to be limited resources available on this topic. Any assistance or guidance would be greatly appreciat ...

Desiring to iterate through an array of identification numbers in order to retrieve information from an external API

I have been working on an app where I retrieve IDs from one API and pass them into a second API to display the property overviewList.overview.lifeTimeData.energy for each ID. However, in my current setup, I am only able to display the property of the fir ...

AJAX Image Upload: How to Transfer File Name to Server?

Has anyone successfully uploaded an image to a web server using AJAX, but struggled with passing the file name and path to the PHP script on the server side? Here is the HTML code along with the JavaScript (ImageUpload01.php) that triggers the PHP: Pleas ...

modify the final attribute's value

Hello I've been using skrollr js to create a parallax website. However, the issue arises when determining the section height, as it depends on the content within. My goal is to locate the last attribute and adjust the number value based on the section ...

What is causing this setInterval function to run repeatedly?

Below is the code snippet from my Vue application: mounted: function () { this.timer = setInterval(async () => { if (this.progress >= 1) { this.progress = 1 clearInterval(this.timer) } console.log('update& ...

Manipulation of every side of a cube or any other shape within three.js

Is there a way to achieve control over individual faces without manually creating a geometry? I am trying to create an explosion effect where each face moves in different dimensions. Can pre-made geometries such as cubes or polyhedrons be disassembled, or ...

Navigating with router.push in Vue.js to the same path but with different query parameters

The existing URL is /?type=1 I am attempting to implement router.push on this specific page. this.$router.push('/?type=2'); However, it results in a NavigationDuplicated error. I prefer not to utilize parameters such as /:type ...

Deactivate all functions of a complete row in the table

I'm working with a table that contains various user interaction controls in its cells, such as buttons and links. I'm looking to gray out certain rows of the table so that all operations related to those rows are disabled. Does anyone have sugge ...

Develop an interactive single-page scrolling system for seamless navigation between points

Creating a navigation that scrolls to the selected element when clicking on an <a> tag is my current project. I want it to animate smoothly during the transition. The navigation should go from: <a href="#Home">Home</a> To: <div id= ...

Ways to retrieve the locale parameter from the URL in Next Js

For my Next Js application, I've successfully implemented multi language support using the next-i18next module. Everything is working smoothly. Below is the code for my NabBar component: const NavBar = ({...props}) => { const router = useRouter( ...