Solution 1 :

Have a look at the JS Fiddle: https://jsfiddle.net/k4u5xew6/

Here you need to take into consideration that, before completion of AJAX request. You won’t be able to get the data retrieved from API inside table & it’s returning “undefined” in JSON. That’s why we have observed AJAX completion using “complete” method of $.ajax. And then after just used your code for retrieving & preparing JSON data, that’s working fine. Check console from JSFiddle.

Reference for “complete” method of $.ajax found at: https://api.jquery.com/jquery.ajax/

JS Code:

$(document).ready(function(){
  getAPIData();
});

function getAPIData() {
  $.ajax({
      url: "https://rest.soilgrids.org/query?lon=72.8397202&lat=19.0010232&attributes=ORCDRC,PHIHOX,PHIKCL,BLDFIE,CLYPPT,SLTPPT,SNDPPT,WWP", 
      type: "GET", 
      dataType: "json", 
      error: function() {
          console.log("Error processing your request");
      }, 
      success: function(response) {
        var bldfiesl1 = response.properties.BLDFIE.M.sl1;
        var bldfiesl2 = response.properties.BLDFIE.M.sl2;
        var bldfiesl3 = response.properties.BLDFIE.M.sl3;
        var bldfiesl4 = response.properties.BLDFIE.M.sl4;
        var bldfiesl5 = response.properties.BLDFIE.M.sl5;
        var bldfiesl6 = response.properties.BLDFIE.M.sl6;
        var bldfiesl7 = response.properties.BLDFIE.M.sl7;
        document.getElementById('bldfiesl1').innerHTML = bldfiesl1;
        document.getElementById('bldfiesl2').innerHTML = bldfiesl2;
        document.getElementById('bldfiesl3').innerHTML = bldfiesl3;
        document.getElementById('bldfiesl4').innerHTML = bldfiesl4;
        document.getElementById('bldfiesl5').innerHTML = bldfiesl5;
        document.getElementById('bldfiesl6').innerHTML = bldfiesl6;
        document.getElementById('bldfiesl7').innerHTML = bldfiesl7;
      }, 
      complete: function() {
        var table = document.getElementById('bulkdensity');
        var json = []; // First row needs to be headers 
        var headers =[];
        for (var i = 0; i < table.rows[0].cells.length; i++) {
          headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi, '');
        }

        // Go through cells 
        for (var i = 1; i < table.rows.length; i++) {
          var tableRow = table.rows[i];
          var rowData = {};
          for (var j = 0; j < tableRow.cells.length; j++) {
            rowData[headers[j]] = tableRow.cells[j].innerHTML;
          }
          json.push(rowData);
        }
        console.log("JSON DATA=", json);
      }
  });
}

Problem :

I am trying to create a chart for the HTML table I created, which stores the values retrieved from a public API.

But before I create the chart, I parse the HTML table first into a JavaScript object, and output it in the console. But it seems that it returns null.

Example table

<div>
  <div>
     <canvas id="bulkdensitychart"></canvas>
  </div>

  <table id="bulkdensity">
    <tr>
        <th>Soil Layer (meter deep)</th>
        <th>Value</th>
    </tr>
    <tr>
        <td>0.00 m</td>
        <td id="bldfiesl1"></td>
    </tr>
    <tr>
        <td>0.05 m</td>
        <td id="bldfiesl2"></td>
    </tr>
    <tr>
        <td>0.15 m</td>
        <td id="bldfiesl3"></td>
    </tr>
    <tr>
        <td>0.30 m</td>
        <td id="bldfiesl4"></td>
    </tr>
    <tr>
        <td>0.60 m</td>
        <td id="bldfiesl5"></td>
    </tr>
    <tr>
        <td>1.00 m</td>
        <td id="bldfiesl6"></td>
    </tr>
    <tr>
        <td>2.00 m</td>
        <td id="bldfiesl7"></td>
    </tr>
  </table>

The script for taking values from API

$(document).ready(function () {
    $("#search").click(function () {
        $("#physical").show();
        let lat = $("#lat").val();
        let long = $("#long").val();
        if (lat == "" || long == "" || lat > 90 || lat < -90 || long > 180 || long < -180) {
            alert("please enter proper latitude and longitude value to get info");
            return;
        }
        else {
            $.ajax({

                type: "GET",
                url: `https://rest.soilgrids.org/query?lon=${long}&lat=${lat}&attributes=ORCDRC,PHIHOX,PHIKCL,BLDFIE,CLYPPT,SLTPPT,SNDPPT,WWP`,
                dataType: "json",
                success: function (response) {
                    if (response.properties.soilmask == "nodata") {
                        alert("No data found :(");
                        return;
                    }
                    else {
                        var bldfiesl1 = response.properties.BLDFIE.M.sl1;
                        var bldfiesl2 = response.properties.BLDFIE.M.sl2;
                        var bldfiesl3 = response.properties.BLDFIE.M.sl3;
                        var bldfiesl4 = response.properties.BLDFIE.M.sl4;
                        var bldfiesl5 = response.properties.BLDFIE.M.sl5;
                        var bldfiesl6 = response.properties.BLDFIE.M.sl6;
                        var bldfiesl7 = response.properties.BLDFIE.M.sl7;
                        document.getElementById('bldfiesl1').innerHTML = bldfiesl1;
                        document.getElementById('bldfiesl2').innerHTML = bldfiesl2;
                        document.getElementById('bldfiesl3').innerHTML = bldfiesl3;
                        document.getElementById('bldfiesl4').innerHTML = bldfiesl4;
                        document.getElementById('bldfiesl5').innerHTML = bldfiesl5;
                        document.getElementById('bldfiesl6').innerHTML = bldfiesl6;
                        document.getElementById('bldfiesl7').innerHTML = bldfiesl7;
                        alert("Data updated");
                    }

                },
                function(jqXHR, exception) {
                    console.log("error");

                }
            })

        }
    })
})

Script for creating chart, and parsing the HTML table four output in the console

function BuildChart(labels, values, chartTitle) {
  var ctx = document.getElementById("bulkdensitychart").getContext('2d');
  var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
      labels: labels, // Our labels
      datasets: [{
        label: chartTitle, // Name the series
        data: values, // Our values
        backgroundColor: [ // Specify custom colors
          'rgba(255, 99, 132, 0.2)',
          'rgba(54, 162, 235, 0.2)',
          'rgba(255, 206, 86, 0.2)',
          'rgba(75, 192, 192, 0.2)',
          'rgba(153, 102, 255, 0.2)',
          'rgba(255, 159, 64, 0.2)',
          'rgba(255, 99, 132, 0.2)'
        ],
        borderColor: [ // Add custom color borders
          'rgba(255,99,132,1)',
          'rgba(54, 162, 235, 1)',
          'rgba(255, 206, 86, 1)',
          'rgba(75, 192, 192, 1)',
          'rgba(153, 102, 255, 1)',
          'rgba(255, 159, 64, 1)',
          'rgba(255,99,132,1)'
        ],
        borderWidth: 1 // Specify bar border width
      }]
    },
    options: {
      responsive: true, // Instruct chart js to respond nicely.
      maintainAspectRatio: false, // Add to prevent default behavior of full-width/height 
    }
  });
  return myChart;
}
var table = document.getElementById('bulkdensity');
var json = []; // First row needs to be headers 
var headers =[];
for (var i = 0; i < table.rows[0].cells.length; i++) {
  headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi, '');
}

// Go through cells 
for (var i = 1; i < table.rows.length; i++) {
  var tableRow = table.rows[i];
  var rowData = {};
  for (var j = 0; j < tableRow.cells.length; j++) {
    rowData[headers[j]] = tableRow.cells[j].innerHTML;
  }

  json.push(rowData);
}

console.log(json);

I haven’t written the code for mapping the values just yet. I want to finish this part first. How to make the values appears in the console?

Comments

Comment posted by trincot

There is no JSON in your question (jQuery hides the real JSON); please read the usage description of the

Comment posted by Muhd Syahiran Ahmad Shahar

so this fall under jquery ?

Comment posted by trincot

My point is: it does not have anything to do with

Comment posted by Muhd Syahiran Ahmad Shahar

AHh i see, my mistake. Im trying to get value of the table to be available in the console, as far as my understanding for the values in the consoles for the table is in JSON

Comment posted by trincot

Did you read the usage description of the

By