Return JSON data in HTML

Asked

Viewed 79 times

1

Person, I need help with a call from an API, which returns a JSON.

I’ve tried several things, but I can’t get the information back in my HTML.

Can anyone support me with some code? I didn’t put here what I used because I used several.

inserir a descrição da imagem aqui

I just need to get the name and the Description. I’ve used the direct name, I used values.name, but nothing worked.

An example of my javascript

var pageCounter = 1;
var animalContainer = document.getElementById("animal-info");
var btn = document.getElementById("btn");

btn.addEventListener("click", function() {
  var ourRequest = new XMLHttpRequest();
  ourRequest.open('GET', '');
  ourRequest.onload = function() {
    if (ourRequest.status >= 200 && ourRequest.status < 400) {
      var ourData = JSON.parse(ourRequest.responseText);
      renderHTML(ourData);
    } else {
      console.log("We connected to the server, but it returned an error.");
    }    
  };
  ourRequest.onerror = function() {
    console.log("Connection error");
  };
  ourRequest.send();
  pageCounter++;
  if (pageCounter > 10) {
    btn.classList.add("hide-me");
  }
});
function renderHTML(data) {
  var htmlString = "";

  for (i = 0; i < data.length; i++) {
    htmlString += "<p>" + data.values[i].name + data.values[i].description;

    htmlString += '.</p>';

  }

  animalContainer.insertAdjacentHTML('beforeend', htmlString);
}
<header>
    <h1>JSON and AJAX</h1>
    <button id="btn">Fetch Info for 3 New Animals</button>
  </header>
  
  <div id="animal-info"></div>

  <script src="js/main.js"></script>

Thank you.

  • 2

    if you’re using data.values[i].name no for should be data.values.length

2 answers

1


As mentioned by @Ricardopunctual in the comment, the problem most likely lies in the following code block:

for (i = 0; i < data.length; i++) {
    htmlString += "<p>" + data.values[i].name + data.values[i].description;

    htmlString += '.</p>';

  }

Are you checking out data.length. If you instantiate an object and try to find a property length of it (unless explicitly stated) will return undefined. In this case, your loop of repetition does not quite execute.

That being so, what corrects the problem:

for (let i = 0; i < data.values.length; i++) {
    htmlString += "<p>" + data.values[i].name + data.values[i].description;

    htmlString += '.</p>';

}

Check the property length (size) of the property values and not of the object data which is your JSON converted from the JSON.parse. The length of property values return the size of the list.

I hope I’ve helped in some way.

  • Ruan, thank you. That’s exactly what you quoted. My problem now is getting the information to a table. It’s all coming together on the same line.

  • I’m getting back from Undefined in the Description field

0

I’m getting back from Undefined in the Description field

inserir a descrição da imagem aqui

I changed the .js. I wasn’t able to evolve with that.

$(document).ready(function() {
  $("#button-buscar-licencas-ambiente").click(function(){
    var urlapi = '';
    var xhttp = new XMLHttpRequest();
    xhttp.open("GET", urlapi, false);
    xhttp.send();
    var obj = JSON.parse(xhttp.responseText);
    var data_map = new Map();
    var index = 0;
      var objLength = obj.values.length;
      for (var i = 0; i < objLength; i++) {
            data_map.set(obj.values[i].name, data_map.get(obj.values[i].name) + obj.values[i].description);
        }
    const objConverted = Object.fromEntries(data_map);      
    var myJSON = JSON.stringify(objConverted); 
    data_map.forEach(montaTabelaLicencas);
    event.preventDefault();  
  });
});



function montaTabelaLicencas(licencasConsumidas, hostGroup) {

  var newRow = $('<tr class="linha-table">');
      var cols = "";

        cols += '<td class="hostgroup" id="hostgroup">' + hostGroup + '</td>';
        cols += '<td class="quantidade" id="quantidade">' + licencasConsumidas + '</td>';

      newRow.append(cols);

       $("#table-licencas").append(newRow); 
        
}; 

  • 1

    Try not to ask other questions as an answer to a previous question, I think it is better to ask another. That said, I believe the problem lies in for, given that it is calling the get of your Map with the value key you are setting during the set. Since he doesn’t exist yet, he returns undefined. : data_map.set(obj.values[i].name, obj.values[i].name + obj.values[i].description);.

  • Thank you Ruan!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.