Building A Table via Javascript from jSon Data and change innerHTML to reflect dynamic data? [solved]


(Alex Steele) #1

I have explored and worked with JSON data recently, and thank you to everyone who is so helpful here. I was able to make a lot of progress!!! Now I have a minor roadblock. IRL I will be dealing with pure JSON, no need to pull in from PHP or anything - and I would like to get the values from this as either an array (if that is the best way) and then create a table which I can then take the entire contents of and switch out an existing HTML table I have in the Hype File.

I have seen this topic discussed but the one entry closest to it was never really answered, so please bear with me if this is repetitive. Although I do want to be recursive :slight_smile:

What happens: the first innerHTML change completes, and everything is OK. But then the second time, when I want to replace the field in HYPE with the newly created HTML table it does not work. I know I am close, I can feel it. I need a nudge in the right direction.

My javascript code is:

   document.getElementById("thisWeeksTable").innerHTML = 'I just changed this again';


  // STORE EACH PERSON AS AN OBJECT IN AN ARRAY
  var thisWeek = [
    {                                              
      todayIs: 'Monday',                              
      employees: 20,
      totalHours: 160,
      cases: 5000,
      casesPerHour: 31.25
    },
    {
      todayIs: 'Tues',                             
      employees: 23,
      totalHours: 198,
      cases: 6425,
      casesPerHour: 32.44
    },
    {
      todayIs: 'Wednesday',                             
      employees: 18,
      totalHours: 177,
      cases: 5214,
      casesPerHour: 29.76
    },
    {
      todayIs: 'Thursday',                             
      employees: 19,
      totalHours: 180,
      cases: 5656,
      casesPerHour: 29.76
    }
  ];

  // CHECKS EACH PERSON AND ADDS THOSE IN RANGE TO ARRAY
  var results = [];                                              
  thisWeek.forEach(function(weekDay) {                          
      results.push(weekDay);                                   
  }
  );

  // LOOP THROUGH NEW ARRAY ADD CONTENT
  var $tableBody = $('<tbody></tbody>');                    // New table body
  for (var i = 0; i < results.length; i++) {                // Loop through matches
    var weekDay = results[i];                               // Store current weekday
    var $row = $('<tr></tr>');                              // Create a row for them
    $row.append($('<td></td>').text(weekDay.todayIs));      // Add their name
    $row.append($('<td></td>').text(weekDay.employees));    // Add emp
    $row.append($('<td></td>').text(weekDay.totalHours));   // Add total hours
    $row.append($('<td></td>').text(weekDay.cases));        // Add their cases
    $row.append($('<td></td>').text(weekDay.casesPerHour)); // Add their cases
    $tableBody.append( $row );                              // Add row to new content
  }

  $('thead').after($tableBody);                             // Add tbody after thead


 document.getElementById("thisWeeksTable").innerHTML = $tableBody;

(Alex Steele) #2

justTable.hype.zip (13.4 KB)


(Loves Hype) #3

This question was literally just asked and one solution using Vue.js might be


(Loves Hype) #4

I haven’t tested it, as I am on my iPad, but given your example there might only be a .html() missing
https://api.jquery.com/html/


(Alex Steele) #5

thank you! i am checking this right now :slight_smile:


(Loves Hype) #6

BTW in vanilla JavaScript it’s easy but with jQuery there is a whole discussion about innerHTML and outerHTML see https://stackoverflow.com/questions/3535284/full-html-of-object-returned-by-jquery-selector


(Alex Steele) #7

OK now I feel rather foolish :sunny: but thanks to MaxZeib I realized what the issues was I did not take the time to import the jquery.js into my file (its just referenced in the straight HTML but I needed to bring it in as a resource and somehow forgot to do that) and after doing that, things work almost exactly as they should with a few minor flaws but the main issue was solved. Thank you!! so Much @MaxZieb because your response showed me exactly what was wrong!


(Alex Steele) #8

OK, this question does have two parts. now I have the hard-coded JSON building a table, I want to extend that to dynamic data. the way I know is to bring in the JSON data. I have had success this in the past and was even able to assign values to the elements on screen via referencing the array position of the elements in JSON. Here is where it gets interesting… I want to bring in the entire JSON string and see it as a variable, which then becomes the variable I use to build the table. Really straightforward, but something is apparently missing. I even thought it would be good to define the var ahead of time before assigning value, but it really doesn’t seem to matter. As you can see from the attachment, it fails. Any help would be enormously appreciated!

    // define first then assign value
    var thisWeek = "";
    var request = new XMLHttpRequest();
    request.open('GET', 'http://myserver.com/myarea/weeks.json', true);



    request.onload = function() {
    if (request.status >= 200 && request.status < 400) {
        var thisWeek = JSON.parse(request.responseText);

        console.log (thisWeek);
     
      } else {
    	 // error occured, do this.

      }
    };

    request.onerror = function() {
    // error occured, do that.
    };

    request.send();

/*  this is commented out, when it is not, it produces beautiful results.  its basically mimicking the JSON file I am trying to load 
    var thisWeek = [
      {
       "id":1,
       "todayIs":"Mon, Sept. 24, 2018",
       "employees":"20",
       "totalHours":"160",
       "cases":"5000",
       "casesPerHour":"31.25",
       "thumbnail":null
       },
      {
       "id":2,
       "todayIs":"Tue, Sept. 25, 2018",
       "employees":"23",
       "totalHours":"198",
       "cases":"6423",
       "casesPerHour":"32.445",
       "thumbnail":null
       },
      {
       "id":3,
       "todayIs":"Wed, Sept. 26, 2018",
       "employees":"23",
       "totalHours":"198",
       "cases":"6423",
       "casesPerHour":"32.445",
       "thumbnail":null
       },
       {
    "id":4,
       "todayIs":"Thu, Sept. 27, 2018",
       "employees":"23",
       "totalHours":"198",
       "cases":"6423",
       "casesPerHour":"32.445",
       "thumbnail":null
       },
       {
    "id":35,
       "todayIs":"Fri, Sept. 28, 2018",
       "employees":"23",
       "totalHours":"198",
       "cases":"6423",
       "casesPerHour":"32.445",
       "thumbnail":null
       }
    ];
*/

(Loves Hype) #9

You have to build the table in the success handler or at least put the build in a function and call it again when receiving fresh data. If your using jQuery instead of vanilla JS look at the Ajax helper functions… there are a lot of examples and tutorials out there.


(Alex Steele) #10

once again, @MaxZieb thank you! Moving this into the success handler worked like a charm. I suppose I need to learn how to use global variables in Javascript, I was thinking that it was global and I surmise its range is limited. also perhaps a refresher in Javascript is in order for me as I am a MySQL/PHP developer and this was my first foray into Javascript in at least three years. So all the help and guidance are ao appreciated and have helped me tremendously!