Html table from json

  • (2 Pages)
  • +
  • 1
  • 2

27 Replies - 1953 Views - Last Post: 12 April 2019 - 10:06 AM

#16 modi123_1   User is online

  • Suitor #2
  • member icon



Reputation: 15106
  • View blog
  • Posts: 60,397
  • Joined: 12-June 08

Re: Html table from json

Posted 28 February 2019 - 10:15 AM

I would use a span with a defined class or id name.
Was This Post Helpful? 1
  • +
  • -

#17 baavgai   User is offline

  • Dreaming Coder
  • member icon


Reputation: 7442
  • View blog
  • Posts: 15,437
  • Joined: 16-October 07

Re: Html table from json

Posted 28 February 2019 - 11:05 AM

I agree with modi123_1, style a class or an id, not an element.

Simply:
<!DOCTYPE html>
<html>
<head>
    <title>Always have a title</title>
    <style>
        .format1, .format2 { border: 1px solid black }
        .format1 p { color: red; font-size: larger; }
    </style>
</head>
<body>
    <div class="format1"><p>Alpha</p><p>Bravo</p></div>
    <div class="format2"><p>Charlie</p><p>Delta</p></div>
</body>
</html>



Note, here all the p in the div will have the formatting, which is usually a pretty good way to style section of page. Indeed, you can usually style divs and spans and not bother with much else, if that's your jam.

Right, to your problem: your browser is doing exactly what you tell it to. If things aren't going as you expect, open up your browser's dev tools and poke around. Start with just the source and the links and make sure you're getting everything you expect. From there, you can dig into the element styles themselves and see what's going on.

If it helps, before you even mess with server output, mock up some pages like the one above with the styling you want. Then you'll have a sanity check that your style is right and may be better able to see where your dynamic rendering is messing up.
Was This Post Helpful? 1
  • +
  • -

#18 wantsToCode   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 15
  • Joined: 25-February 19

Re: Html table from json

Posted 07 March 2019 - 04:42 AM

Hi all! I think I've made some progress, been studying ejs a bit lately. I still have lots of questions I want to solve and thought I'd ask you one of them:

This is my server.js now:

const express = require('express');
const nhl = require('./nhl.json');
const app = express();

// set the view engine to ejs
app.set('view engine', 'ejs');



// index page
app.get('/', function(req, res) {
    res.render('pages/index');
});

// team page
app.get('/teams', function(req, res) {
  let teams = {
  nhl: nhl
};
    res.render('pages/teams', teams);
});

app.listen(8080);
console.log('8080 is the port');





This works fine as long as I have that nhl.json stored on my computer. I'm struggling with that @baavgai instructions. I mean it worked great like that, just don't know how to make it work with ejs. I've tried to get the data from that api straigth but didn't manage to get it work.
Then I tried to write a json first with fs.writeFile but it always throws an error like this: Error: Cannot find module './nhl.json'. So the problem in here must be that it tries to read the json file before it is created? Any tips how I could affect on the order which the statements are executed?
Was This Post Helpful? 0
  • +
  • -

#19 wantsToCode   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 15
  • Joined: 25-February 19

Re: Html table from json

Posted 07 March 2019 - 04:49 AM

Could I use a async function to solve my problem here? Don't know much of them but what I've read it seems to me it might be the solution..
Was This Post Helpful? 0
  • +
  • -

#20 baavgai   User is offline

  • Dreaming Coder
  • member icon


Reputation: 7442
  • View blog
  • Posts: 15,437
  • Joined: 16-October 07

Re: Html table from json

Posted 07 March 2019 - 08:16 AM

Go back to that readAllTheData example I offered. Look closely. It's loading the data you need and using node's ubiquitous callback pattern. That is async.

The require json thing is a little wonky. In your express server you have all the NodeJs tools at your disposal. Load and pre parse your json data for best and most consistent results. Make certain you have all your resources available before the server fires.

Alternately, you could have app.get('/teams' load the json data on demand. In that case, your successful fs.readFile will yield the page you want, else yield a page with error information so you can see what's going on.
Was This Post Helpful? 1
  • +
  • -

#21 wantsToCode   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 15
  • Joined: 25-February 19

Re: Html table from json

Posted 07 March 2019 - 08:24 AM

Thank you for your guidance, I will concentrate and try to solve this.
Was This Post Helpful? 0
  • +
  • -

#22 wantsToCode   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 15
  • Joined: 25-February 19

Re: Html table from json

Posted 11 March 2019 - 02:15 AM

From one problem to another:

Now my app loads the data from api, no problems there and I get the correct team count. Problem is that when I try to put this data to a table in my teams.ejs -file, I get this error:

Cannot read property 'forEach' of undefined



my server.js:

const express = require('express');
//const nhl = require('./nhl.json');
const fs = require('fs');
const axios = require('axios');
const nhl = 'https://statsapi.web.nhl.com/api/v1/teams';
//const standings = require('./standings.json');

readApiData((data) => {
  //just to make sure
  console.log('data read');
  console.log('team count:', data.teams.length);
  const app = express();
  const port = 5000;
  // set the view engine to ejs
  app.set('view engine', 'ejs');

  // use res.render to load up an ejs view file
  // index page
  app.get('/', function(req, res) {
      res.render('pages/index');
  });

  // team page
  app.get('/teams', function(req, res) {
    let teams = {
    nhl: nhl
  };
      res.render('pages/teams', teams);
  });
  app.listen(port, () => console.log(`Running on port ${port}!`));
});


//load the data
function readApiData(callback) {
  axios.get(nhl).then(res => callback(JSON.parse(JSON.stringify(res.data))));
  function failOut(err) {
    console.log(err); return {};
  }
}




teams.ejs:
<!DOCTYPE html>
<html lang="en">
<head>
    <% include ../partials/head %>
</head>
<body class="container">

<header>
    <% include ../partials/header %>
</header>

<main>
<div class="row">
    <div class="col-sm-8">
        <div class="jumbotron">
            <h1>This is where the standings will be</h1>
            <p>Done using node.js + ejs template engine</p>
        </div>
    </div>

<h3><%=nhl.copyright%></h3>

<table class="table table-hovered">
<tbody>
                    <% nhl.teams.forEach((team, index) => { %>
                        <tr>
                            <th scope="row"><%= team.id %></th>
                            <td><%= team.name %></td>

                        </tr>
                    <% }) %>
                </tbody>
                </table>

</div>
</main>

<footer>
    <% include ../partials/footer %>
</footer>

</body>
</html>



Can't figure out what the problem is. The api url seems to work and I can load the data from it and print it to my console. This problem occured first time after I put my
app.get('/', function(req, res) {
      res.render('pages/index');
  });

  // team page
  app.get('/teams', function(req, res) {
    let teams = {
    nhl: nhl
  };
      res.render('pages/teams', teams);
  }); 

inside readApiData function. Is this what's causing the error?
Was This Post Helpful? 0
  • +
  • -

#23 andrewsw   User is online

  • never lube your breaks
  • member icon

Reputation: 6798
  • View blog
  • Posts: 28,092
  • Joined: 12-December 12

Re: Html table from json

Posted 11 March 2019 - 02:30 AM

<% nhl.teams.forEach((team, index) => { %>

The error is stating that 'teams' is undefined. So 'nhl' does not have a 'teams' property.

app.get('/teams', function(req, res) {
    let teams = {
    nhl: nhl
  };

This suggests teams has a property nhl, although I suspect that this local variable drops out of scope.
Was This Post Helpful? 1
  • +
  • -

#24 wantsToCode   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 15
  • Joined: 25-February 19

Re: Html table from json

Posted 11 March 2019 - 03:50 AM

That 'teams' should come from json provided by the api url. It worked with a local json file just fine..

This post has been edited by andrewsw: 11 March 2019 - 03:56 AM
Reason for edit:: removed previous quote, just use the Reply button

Was This Post Helpful? 0
  • +
  • -

#25 andrewsw   User is online

  • never lube your breaks
  • member icon

Reputation: 6798
  • View blog
  • Posts: 28,092
  • Joined: 12-December 12

Re: Html table from json

Posted 11 March 2019 - 04:44 AM

I am not familiar with node, but

app.get('/teams', function(req, res) {
    let teams = {
    nhl: nhl
  };

I would have thought that it was 'res' (response) that would contain the JSON(?). Print out (or examine) the value(s) contained by 'res' to check this.
Was This Post Helpful? 1
  • +
  • -

#26 wantsToCode   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 15
  • Joined: 25-February 19

Re: Html table from json

Posted 11 March 2019 - 06:30 AM

Solved this, was passing the url when I was supposed to pass the data, I think.

Changed this:
 
  // team page
  app.get('/teams', function(req, res) {
    let teams = {
    nhl: nhl
  };
      res.render('pages/teams', teams);
  }); 



to this:

 
  // team page
  app.get('/teams', function(req, res) {
    let teams = {
    nhl: data
  };
      res.render('pages/teams', teams);
  }); 



It worked!
Was This Post Helpful? 0
  • +
  • -

#27 wantsToCode   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 15
  • Joined: 25-February 19

Re: Html table from json

Posted 11 April 2019 - 10:45 PM

Hi all. Need some help because I can't figure out how I should approach this problem.

I have these two functions...:

function readStandingsData(callback) {
  axios({
      method:'get',
      url: standings,
      auth: {
          username: '*****',
          password: '*****'
      }
  })
  .then(res => callback(JSON.parse(JSON.stringify(res.data))));
  function failOut(err) {
    console.log(err); return {};
  }
}



function readConfStandingsData(callback) {
  axios({
      method:'get',
      url: standingsByConf,
      auth: {
          username: '*****',
          password: '*****'
      }
  })
  .then(res => callback(JSON.parse(JSON.stringify(res.data))));
  function failOut(err) {
    console.log(err); return {};
  }
}




...and here are the url's what those functions uses:

const standings = 'https://api.mysportsfeeds.com/v1.2/pull/nhl/2018-2019-regular/overall_team_standings.json';
const standingsByConf = 'https://api.mysportsfeeds.com/v1.2/pull/nhl/2018-2019-regular/conference_team_standings.json';



I'm using axios there to get the data from api and because it's username and password protected I need to authenticate it.
Everything above works well, I can load and render the overall standings table from that first api. I render my standings page inside the readStandingsData function like this:

readStandingsData((data) => {

  // standings page
  app.get('/standings', (req, res) => {
    const records = {
    standings: data
  };

      res.render('pages/standings', records);
  });
});



Like I said, that works well. My problem is that I'm trying to get NHL standings by conference (the second api and function) to the same standings page and I can't figure out how to do it. Like you see, I did own functions for both api calls but because I'm rendering the standings page inside the readStandingsData -function, I don't know how to use readConfStandingsData -function on that same page. I've tried to solve this by studying how to chain api calls with axios but can't seem to get it right, maybe it's that authentication what cofuses me.

I tried to be as clear as I could, I hope you understand what I'm trying to say here. Please feel free to ask anything if you don't. Would appreciate greatly any help. Would really like to move on from this problem.
Was This Post Helpful? 0
  • +
  • -

#28 ArtificialSoldier   User is offline

  • D.I.C Lover
  • member icon

Reputation: 2332
  • View blog
  • Posts: 7,107
  • Joined: 15-January 14

Re: Html table from json

Posted 12 April 2019 - 10:06 AM

You might need to check the documentation for axios to see what your options are, but one option may be to have another function that gets called after the records come back from each one, and that function will need to make sure that you have all the records you need from both calls and then render the page if you have everything. Otherwise, maybe there's a way you can update part of the page with axios or express.
Was This Post Helpful? 1
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2