Search code examples
javascriptajaxdomjavascript-objects

JavaScript: Building table from AJAX response using DOM


I sending an AJAX request and I'm getting a JSON object as a response. I am trying to put the data in the JSON object into a table using the DOM API. Currently it is not working at all.

Can someone help me out with the logic of creating a table with DOM in this way? The wrong code I have tried writing is here:

// AJAX request 

var xhttp = new XMLHttpRequest();
var fulldata;

xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    fulldata = JSON.parse(this.responseText);
  }
}

xhttp.open("GET", "https://raw.githubusercontent.com/attainu-falcon/falcon-course-module/master/coding-challenges/data/books.json ", true);
xhttp.send();

// creating table using DOM

var table = document.createElement('table');
table.setAttribute('class', 'tbl') document.querySelector('.div2').appendChild(table);

// from here nothing is working and I don't understand what to do. 

for (var i = 0; i < fulldata.length; i++) {
  var rows = document.createElement('tr');
  document.querySelector('.tbl').appendChild(rows);

  var cols = document.createElement('td');
  document.querySelector('.tbl tr').appendChild(cols);

  rows.innerHTML = < td > fulldata[i].author < /td>;
  rows.innerHTML = < td > fulldata[i].language < /td>;

}

Solution

  • The main issue here is that your code seems to expect the network request to be synchronous (ie, that fulldata is populated after the xhttp.send() function call has been issued).

    In order for your code to work as required, you should instead build the table "inside" of the onreadystatechange function handler (ie at the point when fulldata is populated). One approach to this would be as follows:

    // Define a helper function that creates and populates a
    // table based on the provided json data
    function buildTable(rows) {
    
      // Create the table    
      var table = document.createElement('table');
      table.classList.add('tbl');
    
      // Attach the table to document
      document.querySelector('.div2').appendChild(table);
    
      // Iterate each row of json data and insert row/cells
      // with author and language values of each row
      json.forEach(({ author, language }) => {
    
        let row = table.insertRow()
    
        row.insertCell().innerText = author
        row.insertCell().innerText = language
      })
    }
    
    var xhttp = new XMLHttpRequest();
    
    // This function is called when a response is returned 
    // from the AJAX request. This is the "asynchronous callback"
    xhttp.onreadystatechange = function() {
    
      if (this.readyState == 4 && this.status == 200) {
    
        // If we reach this point, the request is understood to be
        // successful and we process the responseText as JSON and 
        // build the table
        buildTable(JSON.parse(this.responseText));
      }
    }
    
    // Execute the AJXA request
    xhttp.open("GET", "https://raw.githubusercontent.com/attainu-falcon/falcon-course-module/master/coding-challenges/data/books.json", true);
    xhttp.send();
    

    Here's a working example - hope that helps!